From 09f524d1eed2248e7524f6d2eab3ae0f84360893 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Thu, 16 Jan 2025 16:59:30 +0530 Subject: [PATCH 01/24] SK-1821: Refactor release pipelines (#153) * SK-1821: Refactor release pipelines --- .github/workflows/shared-build-and-deploy.yml | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 7d94b14f..1b0309dd 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -27,6 +27,22 @@ jobs: python -m pip install --upgrade pip pip install setuptools wheel twine + - name: Resolve Branch for the Tagged Commit + id: resolve-branch + if: ${{ inputs.tag == 'beta' || inputs.tag == 'public' }} + run: | + TAG_COMMIT=$(git rev-list -n 1 ${{ github.ref_name }}) + + BRANCH_NAME=$(git branch -r --contains $TAG_COMMIT | grep -o 'origin/.*' | sed 's|origin/||' | head -n 1) + + if [ -z "$BRANCH_NAME" ]; then + echo "Error: Could not resolve branch for the tag." + exit 1 + fi + + echo "Resolved Branch Name: $BRANCH_NAME" + echo "branch_name=$BRANCH_NAME" >> $GITHUB_ENV + - name: Get Previous tag id: previoustag uses: WyriHaximus/github-action-get-previous-tag@v1 @@ -43,23 +59,27 @@ jobs: fi - name: Commit changes - if: ${{ inputs.tag == 'internal' || inputs.tag == 'public' }} run: | git config user.name "${{ github.actor }}" git config user.email "${{ github.actor }}@users.noreply.github.com" + + if [[ "${{ inputs.tag }}" == "beta" || "${{ inputs.tag }}" == "public" ]]; then + git checkout ${{ env.branch_name }} + fi + git add setup.py git add skyflow/utils/_version.py - if [ "${{ inputs.tag }}" = "internal" ]; then + if [[ "${{ inputs.tag }}" == "internal" ]]; then VERSION="${{ steps.previoustag.outputs.tag }}.dev0+$(git rev-parse --short $GITHUB_SHA)" COMMIT_MESSAGE="[AUTOMATED] Private Release $VERSION" git commit -m "$COMMIT_MESSAGE" git push origin ${{ github.ref_name }} -f fi - if [ "${{ inputs.tag }}" = "public" ]; then + if [[ "${{ inputs.tag }}" == "beta" || "${{ inputs.tag }}" == "public" ]]; then COMMIT_MESSAGE="[AUTOMATED] Public Release - ${{ steps.previoustag.outputs.tag }}" git commit -m "$COMMIT_MESSAGE" - git push origin + git push origin ${{ env.branch_name }} fi - name: Build and Publish Package From e923868a5f36647248098de6f516475a7ece8b54 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Fri, 7 Feb 2025 12:55:18 +0530 Subject: [PATCH 02/24] SK-1863: Added a migration guide section in the README for transitioning from v1 to v2. (#155) * SK-1863: Added migration from v1 to v2 section in readme --- README.md | 244 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) diff --git a/README.md b/README.md index bfdab7a3..f3d07545 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ This Python SDK is designed to help developers easily implement Skyflow into the - [Requirements](#requirements) - [Configuration](#configuration) - [Service Account Bearer Token Generation](#service-account-bearer-token-generation) + - [Migration from v1 to v2](#migrate-from-v1-to-v2) - [Vault APIs](#vault-apis) - [Insert data into the vault](#insert-data-into-the-vault) - [Detokenize](#detokenize) @@ -328,6 +329,249 @@ try: except SkyflowError as e: print(e) ``` +## Migrate from V1 to V2 + +Below are the steps to migrate the Python SDK from V1 to V2. + +### 1. Authentication Options + +In V2, we have introduced multiple authentication options. +You can now provide credentials in the following ways: + +- **API Key (Recommended)** +- **Environment Variable** (`SKYFLOW_CREDENTIALS`) (**Recommended**) +- **Path to your credentials JSON file** +- **Stringified JSON of your credentials** +- **Bearer token** + +These options allow you to choose the authentication method that best suits your use case. + +#### V1 (Old): +Passing the token provider function below as a parameter to the Configuration. + +```python +# User defined function to provide access token to the vault apis +def token_provider(): + global bearerToken + if !(is_expired(bearerToken)): + return bearerToken + bearerToken, _ = generate_bearer_token('') + return bearerToken +``` + +#### V2 (New): +Passing one of the following: + +```python +# Option 1: API Key (Recommended) +credentials = { + 'api_key': '', # API key +} + +# Option 2: Environment Variables (Recommended) +# Set SKYFLOW_CREDENTIALS in your environment + +# Option 3: Credentials File +credentials = { + 'path': '', # Path to credentials file +} + +# Option 4: Stringified JSON +credentials = { + 'credentials_string': '', # Credentials as string +} + +# Option 5: Bearer Token +credentials = { + 'token': '', # Bearer token +} +``` + +**Notes:** +- Use only ONE authentication method. +- API Key or Environment Variables are recommended for production use. +- Secure storage of credentials is essential. +- For overriding behavior and priority order of credentials, please refer to the README. + +### 2. Client Initialization + +In V2, we have introduced a Builder design pattern for client initialization and added support for multi-vault. This allows you to configure multiple vaults during client initialization. + +In V2, the log level is tied to each individual client instance. + +During client initialization, you can pass the following parameters: + +- **`vault_id`** and **`cluster_id`**: These values are derived from the vault ID & vault URL. +- **`env`**: Specify the environment (e.g., SANDBOX or PROD). +- **`credentials`**: The necessary authentication credentials. + +#### V1 (Old): + +```python +# Initializing a Skyflow Client instance with a SkyflowConfiguration object +config = Configuration('', '', token_provider) +client = Client(config) +``` + +#### V2 (New): + +```python +# Initializing a Skyflow Client instance +client = ( + Skyflow.builder() + .add_vault_config({ + 'vault_id': '', # Primary vault + 'cluster_id': '', # ID from your vault URL e.g., https://{clusterId}.vault.skyflowapis.com + 'env': Env.PROD, # Env by default it is set to PROD + 'credentials': credentials # Individual credentials + }) + .add_skyflow_credentials(credentials) # Skyflow credentials will be used if no individual credentials are passed + .set_log_level(LogLevel.INFO) # set log level by default it is set to ERROR + .build() +) +``` + +**Key Changes:** +- `vault_url` replaced with `cluster_Id`. +- Added environment specification (`env`). +- Instance-specific log levels. + +### 3. Request & Response Structure + +In V2, with the introduction of constructor parameters, you can now pass parameters to `InsertRequest`. This request need +- **`table_name`**: The name of the table. +- **`values`**: An array of objects containing the data to be inserted. +The response will be of type `InsertResponse` class, which contains `inserted_fields` and errors. + +#### V1 (Old): Request Building + +```python +client.insert( + { + "records": [ + { + "table": "cards", + "fields": { + "cardNumber": "41111111111", + "cvv": "123", + }, + } + ] + }, + InsertOptions(True), +) +``` + +#### V2 (New): Request Building + +```python +# Prepare Insertion Data +insert_data = [ + { + 'card_number': '', + 'cvv': '', + }, +] + +table_name = '' # Replace with your actual table name + +# Create Insert Request +insert_request = InsertRequest( + table_name=table_name, + values=insert_data, + return_tokens=True, # Optional: Get tokens for inserted data + continue_on_error=True # Optional: Continue on partial errors +) + +# Perform Secure Insertion +response = skyflow_client.vault(primary_vault_config.get('')).insert(insert_request) +``` + +#### V1 (Old): Response Structure + +```json +{ + "records": [ + { + "table": "cards", + "fields": { + "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", + "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", + "skyflow_id": "d863633c-8c75-44fc-b2ed-2b58162d1117" + }, + "request_index": 0 + } + ] +} +``` + +#### V2 (New): Response Structure + +```python +InsertResponse( + inserted_fields=[ + { + 'skyflow_id': 'a8f3ed5d-55eb-4f32-bf7e-2dbf4b9d9097', + 'card_number': '5479-4229-4622-1393' + } + ], + errors=[] +) +``` + +### 4. Request Options + +In V2, we have introduced constructor parameters, allowing you to set options as key-value pairs as parameters in request. + +#### V1 (Old): + +```python +options = InsertOptions( + tokens = True +) +``` + +#### V2 (New): + +```python +insert_request = InsertRequest( + table_name=table_name, + values=insert_data, + return_tokens=True, # Optional: Get tokens for inserted data + continue_on_error=True # Optional: Continue on partial errors +) +``` + +### 5. Request Options + +In V2, we have enriched the error details to provide better debugging capabilities. +The error response now includes: +- **http_status**: The HTTP status code. +- **grpc_code**: The gRPC code associated with the error. +- **details & message**: A detailed description of the error. +- **request_id**: A unique request identifier for easier debugging. + +#### V1 (Old) Error Structure: + +```json +{ + "code": "", + "message": "" +} +``` + +#### V2 (New) Error Structure: + +```json +{ + "http_status": "", + "grpc_code": "", + "http_code": "", + "message": "", + "request_id": "", + "details": [ "
" ] +} +``` ## Vault APIs From aca63e1be5e22a960197a8de12dcf70351b3ab9d Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Tue, 18 Feb 2025 10:40:22 +0530 Subject: [PATCH 03/24] SK-1894: Update README for Python SDK V2 (#157) * SK-1894: Update readme --- README.md | 2193 +++++++++++++++++++++++++++++++++++------------------ 1 file changed, 1476 insertions(+), 717 deletions(-) diff --git a/README.md b/README.md index f3d07545..af1e79f4 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,61 @@ -# Skyflow-python +# Skyflow Python ---- - -## Description - -This Python SDK is designed to help developers easily implement Skyflow into their python backend. +The Skyflow Python SDK is designed to help with integrating Skyflow into a Python backend. ## Table of Contents -- [Skyflow-python](#skyflow-python) - - [Description](#description) - - [Table of Contents](#table-of-contents) - - [Features](#features) - - [Installation](#installation) +- [Table of Contents](#table-of-contents) +- [Overview](#overview) +- [Install](#installation) - [Requirements](#requirements) - [Configuration](#configuration) - - [Service Account Bearer Token Generation](#service-account-bearer-token-generation) - - [Migration from v1 to v2](#migrate-from-v1-to-v2) - - [Vault APIs](#vault-apis) +- [Migration from v1 to v2](#migration-from-v1-to-v2) + - [Authentication options](#1-authentication-options) + - [Initializing the client](#2-initializing-the-client) + - [Request & response structure](#3-request--response-structure) + - [Request options](#4-request-options) + - [Error structure](#5-error-structure) +- [Quickstart](#quickstart) + - [Authenticate](#authenticate) + - [Initialize the client](#initialize-the-client) + - [Insert data into the vault](#insert-data-into-the-vault) +- [Vault](#vault-apis) - [Insert data into the vault](#insert-data-into-the-vault) - [Detokenize](#detokenize) - [Tokenize](#tokenize) - [Get](#get) - - [Get By Id](#get-by-id) - - [Redaction Types](#redaction-types) + - [Get by skyflow IDs](#get-by-skyflow-ids) + - [Get tokens](#get-tokens) + - [Get by column name and column values](#get-by-column-name-and-column-values) + - [Redaction types](#redaction-types) - [Update](#update) - [Delete](#delete) - [Invoke Connection](#invoke-connection) - [Query](#query) - - [Logging](#logging) - - [Reporting a Vulnerability](#reporting-a-vulnerability) +- [Connections](#connections) + - [Invoke a connection](#invoke-a-connection) +- [Authenticate with bearer tokens](#authenticate-with-bearer-tokens) + - [Generate a bearer token](#generate-a-bearer-token) + - [Generate bearer tokens with context](#generate-bearer-tokens-with-context) + - [Generate scoped bearer tokens](#generate-scoped-bearer-tokens) + - [Generate signed data tokens](#generate-signed-data-tokens) +- [Logging](#logging) +- [Reporting a Vulnerability](#reporting-a-vulnerability) + +## Overview -## Features +- Authenticate using a Skyflow service account and generate bearer tokens for secure access. -Authentication with a Skyflow Service Account and generation of a bearer token +- Perform Vault API operations such as inserting, retrieving, and tokenizing sensitive data with ease. -Vault API operations to insert, retrieve and tokenize sensitive data +- Invoke connections to third-party APIs without directly handling sensitive data, ensuring compliance and data protection. -Invoking connections to call downstream third party APIs without directly handling sensitive data ## Installation ### Requirements -- Python 3.8.0 and above +- Python 3.8.0 and above (tested with Python 3.8.0) ### Configuration @@ -52,302 +64,24 @@ The package can be installed using pip: ```bash pip install skyflow ``` - -## Service Account Bearer Token Generation - -The [Service Account](https://github.com/skyflowapi/skyflow-python/tree/main/skyflow/service_account) python module is used to generate service account tokens from service account credentials file which is downloaded upon creation of service account. The token generated from this module is valid for 60 minutes and can be used to make API calls to vault services as well as management API(s) based on the permissions of the service account. - -The `generate_bearer_token(filepath)` function takes the credentials file path for token generation, alternatively, you can also send the entire credentials as string, by using `generate_bearer_token_from_creds(credentials)` - -[Example using filepath](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/token_generation_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -def token_provider(): - global bearer_token - global token_type - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_toke('') - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) - -``` - -[Example using credentials string](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/token_generation_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, generate_bearer_token_from_creds, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -def token_provider(): - global bearer_token - global token_type - # As an example - skyflow_credentials = { - 'clientID': '', - 'clientName': '', - 'tokenURI': '', - 'keyID': '', - 'privateKey': '', - } - credentials_string = json.dumps(skyflow_credentials) - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_token_from_creds(skyflow_credentials_string) - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) - -``` - -## Service Account Scoped Token Generation - -[Example using filepath](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/scoped_token_generation_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -options = { - 'role_ids': ['ROLE_ID1', 'ROLE_ID2'] -} -def token_provider(): - global bearer_token - global token_type - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_token('', options) - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) - -``` - -[Example using credentials string](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/scoped_token_generation_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, generate_bearer_token_from_creds, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -options = { - 'role_ids': ['ROLE_ID1', 'ROLE_ID2'] -} -def token_provider(): - global bearer_token - global token_type - # As an example - skyflow_credentials = { - 'clientID': '', - 'clientName': '', - 'tokenURI': '', - 'keyID': '', - 'privateKey': '', - } - credentials_string = json.dumps(skyflow_credentials) - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_token_from_creds(skyflow_credentials_string, options) - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) - -``` - -## Service Account Token Generation With Context - -[Example using filepath](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/token_generation_with_context_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -options = { - 'ctx': "" -} -def token_provider(): - global bearer_token - global token_type - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_token('', options) - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) - -``` - -[Example using credentials string](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/token_generation_with_context_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, generate_bearer_token_from_creds, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -options = { - 'ctx': '' -} -def token_provider(): - global bearer_token - global token_type - # As an example - skyflow_credentials = { - 'clientID': '', - 'clientName': '', - 'tokenURI': '', - 'keyID': '', - 'privateKey': '', - } - credentials_string = json.dumps(skyflow_credentials) - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_token_from_creds(skyflow_credentials_string, options) - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) - -``` - -## Service Account Signed Token Generation - -[Example using filepath](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/signed_token_generation_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -options = { - 'ctx': 'CONTEX_ID', - 'data_tokens': ['DATA_TOKEN1', 'DATA_TOKEN2'], - 'time_to_live': 90 # in seconds -} -def token_provider(): - global bearer_token - global token_type - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_token('', options) - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) - -``` - -[Example using credentials string](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/service_account/signed_token_generation_example.py): - -```python -from skyflow.error import SkyflowError -from skyflow.service_account import generate_bearer_token, generate_bearer_token_from_creds, is_expired - -# cache token for reuse -bearer_token = '' -token_type = '' -options = { - 'ctx': 'CONTEX_ID', - 'data_tokens': ['DATA_TOKEN1', 'DATA_TOKEN2'], - 'time_to_live': 90 # in seconds -} -def token_provider(): - global bearer_token - global token_type - # As an example - skyflow_credentials = { - 'clientID': '', - 'clientName': '', - 'tokenURI': '', - 'keyID': '', - 'privateKey': '', - } - credentials_string = json.dumps(skyflow_credentials) - - if is_expired(bearer_token): - bearer_token, token_type = generate_bearer_token_from_creds(skyflow_credentials_string, options) - return bearer_token, token_type - -try: - bearer_token, token_type = token_provider() - print('Access Token:', bearer_token) - print('Type of token:', token_type) -except SkyflowError as e: - print(e) -``` -## Migrate from V1 to V2 +## Migration from V1 to V2 Below are the steps to migrate the Python SDK from V1 to V2. -### 1. Authentication Options +### Authentication Options In V2, we have introduced multiple authentication options. You can now provide credentials in the following ways: -- **API Key (Recommended)** -- **Environment Variable** (`SKYFLOW_CREDENTIALS`) (**Recommended**) +- **Passing credentials in ENV.** (`SKYFLOW_CREDENTIALS`) (**Recommended**) +- **API Key** - **Path to your credentials JSON file** - **Stringified JSON of your credentials** - **Bearer token** These options allow you to choose the authentication method that best suits your use case. -#### V1 (Old): -Passing the token provider function below as a parameter to the Configuration. +#### V1 (Old): Passing the token provider function below as a parameter to the Configuration. ```python # User defined function to provide access token to the vault apis @@ -359,8 +93,7 @@ def token_provider(): return bearerToken ``` -#### V2 (New): -Passing one of the following: +#### V2 (New): Passing one of the following: ```python # Option 1: API Key (Recommended) @@ -391,9 +124,9 @@ credentials = { - Use only ONE authentication method. - API Key or Environment Variables are recommended for production use. - Secure storage of credentials is essential. -- For overriding behavior and priority order of credentials, please refer to the README. +- For overriding behavior and priority order of credentials, please refer to [Initialize the client](#initialize-the-client) section in [Quickstart](#quickstart). -### 2. Client Initialization +### Initializing the client In V2, we have introduced a Builder design pattern for client initialization and added support for multi-vault. This allows you to configure multiple vaults during client initialization. @@ -409,7 +142,7 @@ During client initialization, you can pass the following parameters: ```python # Initializing a Skyflow Client instance with a SkyflowConfiguration object -config = Configuration('', '', token_provider) +config = Configuration('', '', token_provider) client = Client(config) ``` @@ -436,7 +169,7 @@ client = ( - Added environment specification (`env`). - Instance-specific log levels. -### 3. Request & Response Structure +### Request & Response Structure In V2, with the introduction of constructor parameters, you can now pass parameters to `InsertRequest`. This request need - **`table_name`**: The name of the table. @@ -519,7 +252,7 @@ InsertResponse( ) ``` -### 4. Request Options +### Request Options In V2, we have introduced constructor parameters, allowing you to set options as key-value pairs as parameters in request. @@ -535,20 +268,23 @@ options = InsertOptions( ```python insert_request = InsertRequest( - table_name=table_name, + table_name=table_name, # Replace with the table name values=insert_data, - return_tokens=True, # Optional: Get tokens for inserted data - continue_on_error=True # Optional: Continue on partial errors + return_tokens=False, # Do not return tokens + continue_on_error=False, # Stop inserting if any record fails + upsert='', # Replace with the column name used for upsert logic + token_mode=TokenMode.DISABLE, # Disable BYOT + tokens='' # Replace with tokens when TokenMode is ENABLE. ) ``` -### 5. Request Options +### Error Structure In V2, we have enriched the error details to provide better debugging capabilities. The error response now includes: - **http_status**: The HTTP status code. - **grpc_code**: The gRPC code associated with the error. -- **details & message**: A detailed description of the error. +- **details** & **message**: A detailed description of the error. - **request_id**: A unique request identifier for easier debugging. #### V1 (Old) Error Structure: @@ -562,119 +298,201 @@ The error response now includes: #### V2 (New) Error Structure: -```json +```typescript { "http_status": "", - "grpc_code": "", - "http_code": "", + "grpc_code": , + "http_code": , "message": "", - "request_id": "", + "request_id": "", "details": [ "
" ] } ``` -## Vault APIs +## Quickstart +Get started quickly with the essential steps: authenticate, initialize the client, and perform a basic vault operation. This section provides a minimal setup to help you integrate the SDK efficiently. -The vault python module is used to perform operations on the vault such as inserting records, detokenizing tokens, retrieving tokens for a skyflow_id and to invoke a connection. - -To use this module, the skyflow client must first be initialized as follows. +### Authenticate +You can use an API key to authenticate and authorize requests to an API. For authenticating via bearer tokens and different supported bearer token types, refer to the [Authenticate with bearer tokens](#authenticate-with-bearer-tokens) section. ```python -from skyflow import Env -from skyflow import Skyflow, LogLevel - -# To generate Bearer Token from credentials string. -skyflow_credentials = { - 'clientID': '', - 'clientName': '', - 'tokenURI': '', - 'keyID': '', - 'privateKey': '', - } -credentials_string = json.dumps(skyflow_credentials) - -# Pass one of api_key, token, credentials_string & path as credentials +# create a new credentials dictionary credentials = { - 'token': 'BEARER_TOKEN', # bearer token - # api_key: "API_KEY", # API_KEY - # path: "PATH", # path to credentials file - # credentials_string: credentials_string, # credentials as string + api_key: "", # add your API key in credentials } - -client = ( - Skyflow.builder() - .add_vault_config({ - 'vault_id': 'VAULT_ID', # primary vault - 'cluster_id': 'CLUSTER_ID', # ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - 'env': Env.PROD, # Env by default it is set to PROD - 'credentials': credentials # individual credentials - }) - .add_skyflow_credentials(credentials) # skyflow credentials will be used if no individual credentials are passed - .set_log_level(LogLevel.INFO) # set log level by default it is set to ERROR - .build() -) ``` -Notes: +### Initialize the client -- If both Skyflow common credentials and individual credentials at the configuration level are provided, the individual credentials at the configuration level will take priority. +To get started, you must first initialize the skyflow client. While initializing the skyflow client, you can specify different types of credentials. +**1. API keys** +- A unique identifier used to authenticate and authorize requests to an API. -All Vault APIs must be invoked using a client instance. +**2. Bearer tokens** +- A temporary access token used to authenticate API requests, typically included in the +Authorization header. -### Insert data into the vault +**3. Service account credentials file path** +- The file path pointing to a JSON file containing credentials for a service account, used +for secure API access. -To insert data into your vault, use the `insert` method. The `InsertRequest` class is used to create an insert request, which contains the values to be inserted in the form of a dictionary of records. Additionally, you can provide options in the insert request, such as returning tokenized data, upserting records, and continuing on error. +**4. Service account credentials string** +- A JSON-formatted string containing service account credentials, often used as an alternative to a file for programmatic authentication. -Insert call schema +Note: Only one type of credential can be used at a time. ```python -#Initialize Client -from skyflow.error import SkyflowError -from skyflow.vault.data import InsertRequest +import json +from skyflow import Skyflow +from skyflow import LogLevel +from skyflow import Env -try: - insert_data = [ - {'': ''}, - {'': ''} - ] +""" +Example program to initialize the Skyflow client with various configurations. +The Skyflow client facilitates secure interactions with the Skyflow vault, +such as securely managing sensitive data. +""" + +# Step 1: Define the primary credentials for authentication. +# Note: Only one type of credential can be used at a time. You can choose between: +# - API key +# - Bearer token +# - A credentials string (JSON-formatted) +# - A file path to a credentials file. + +# Initialize primary credentials using a Bearer token for authentication. +primary_credentials = { + 'token': '' # Replace with your actual authentication token. +} +# Step 2: Configure the primary vault details. +# VaultConfig stores all necessary details to connect to a specific Skyflow vault. +primary_vault_config = { + 'vault_id': '', # Replace with your primary vault's ID. + 'cluster_id': '', # Replace with the cluster ID (part of the vault URL, e.g., https://{clusterId}.vault.skyflowapis.com). + 'env': Env.PROD, # Set the environment (PROD, SANDBOX, STAGE, DEV). + 'credentials': primary_credentials # Attach the primary credentials to this vault configuration. +} - insert_request = InsertRequest( - table_name = '', - values = insert_data, - ) +# Step 3: Create credentials as a JSON object (if a Bearer Token is not provided). +# Demonstrates an alternate approach to authenticate with Skyflow using a credentials object. +skyflow_credentials = { + 'clientID': '', # Replace with your Client ID. + 'clientName': '', # Replace with your Client Name. + 'tokenURI': '', # Replace with the Token URI. + 'keyID': '', # Replace with your Key ID. + 'privateKey': '' # Replace with your Private Key. +} + +# Step 4: Convert the JSON object to a string and use it as credentials. +# This approach allows the use of dynamically generated or pre-configured credentials. +credentials_string = json.dumps(skyflow_credentials) # Converts JSON object to string for use as credentials. + +# Step 5: Define secondary credentials (API key-based authentication as an example). +# Demonstrates a different type of authentication mechanism for Skyflow vaults. +secondary_credentials = { + 'token': '' # Replace with your API Key for authentication. +} + +# Step 6: Configure the secondary vault details. +# A secondary vault configuration can be used for operations involving multiple vaults. +secondary_vault_config = { + 'vault_id': '', # Replace with your secondary vault's ID. + 'cluster_id': '', # Replace with the corresponding cluster ID. + 'env': Env.PROD, # Set the environment for this vault. + 'credentials': secondary_credentials # Attach the secondary credentials to this configuration. +} + +# Step 7: Define tertiary credentials using a path to a credentials JSON file. +# This method demonstrates an alternative authentication method. +tertiary_credentials = { + 'token': '' # Replace with the path to your credentials file. +} + +# Step 8: Configure the tertiary vault details. +tertiary_vault_config = { + 'vault_id': '', # Replace with the tertiary vault ID. + 'cluster_id': '', # Replace with the corresponding cluster ID. + 'env': Env.PROD, # Set the environment for this vault. + 'credentials': tertiary_credentials # Attach the tertiary credentials. +} + +# Step 9: Build and initialize the Skyflow client. +# Skyflow client is configured with multiple vaults and credentials. +skyflow_client = ( + Skyflow.builder() + .add_vault_config(primary_vault_config) # Add the primary vault configuration. + .add_vault_config(secondary_vault_config) # Add the secondary vault configuration. + .add_vault_config(tertiary_vault_config) # Add the tertiary vault configuration. + .add_skyflow_credentials(skyflow_credentials) # Add JSON-formatted credentials if applicable. + .set_log_level(LogLevel.ERROR) # Set log level for debugging or monitoring purposes. + .build() +) + +# The Skyflow client is now fully initialized. +# Use the `skyflow_client` object to perform secure operations such as: +# - Inserting data +# - Retrieving data +# - Deleting data +# within the configured Skyflow vaults. - response = skyflow_client.vault('VAULT_ID').insert(insert_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) ``` +Notes +- If both Skyflow common credentials and individual credentials at the configuration level are specified, the individual credentials at the configuration level will take precedence. +- If neither Skyflow common credentials nor individual configuration-level credentials are provided, the SDK attempts to retrieve credentials from the SKYFLOW_CREDENTIALS environment variable. +- All Vault operations require a client instance. -**Insert call [example](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/insert_records.py)** +### Insert data into the vault +To insert data into your vault, use the `insert` method. The `InsertRequest` class creates an insert request, which includes the values to be inserted as a list of records. Below is a simple example to get started. For advanced options, check out [Insert data into the vault](#insert-data-into-the-vault-1) section. ```python from skyflow.error import SkyflowError from skyflow.vault.data import InsertRequest +""" + * This example demonstrates how to insert sensitive data (e.g., card information) into a Skyflow vault using the Skyflow client. + * + * 1. Initializes the Skyflow client. + * 2. Prepares a record with sensitive data (e.g., card number and cardholder name). + * 3. Creates an insert request for inserting the data into the Skyflow vault. + * 4. Prints the response of the insert operation. +""" + try: + # Step 1: Initialize data to be inserted into the Skyflow vault insert_data = [ - {'card_number': '4111111111111111'}, + { + 'card_number': '4111111111111111', # Replace with actual card number (sensitive data) + 'cardholder_name': 'John Doe', # Replace with actual cardholder name (sensitive data) + }, ] + # Step 2: Create Insert Request insert_request = InsertRequest( - table_name = 'table1', - values = insert_data, - return_tokens = True # returns tokens + table_name='table1', # Specify the table in the vault where the data will be inserted + values=insert_data, # Attach the data (records) to be inserted + return_tokens=True, # Specify if tokens should be returned upon successful insertion + continue_on_error=True # Optional: Continue on partial errors ) - response = client.vault('').insert(insert_request) - print("Response:", response) -except SkyflowError as e: - print("Error Occurred:", e) + # Step 3: Perform the insert operation using the Skyflow client + insert_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').insert(insert_request) + # Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID -``` + # Step 4: Print the response from the insert operation + print('Insert Response: ', insert_response) -Skyflow returns tokens for the record you just inserted. +except SkyflowError as error: + # Step 5: Handle any exceptions that may occur during the insert operation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes +``` +Skyflow returns tokens for the record that was just inserted. ```python InsertResponse( @@ -682,37 +500,131 @@ InsertResponse( [ { 'skyflow_id': 'a8f3ed5d-55eb-4f32-bf7e-2dbf4b9d9097', - 'card_number': '5479-4229-4622-1393' + 'card_number': '5484-7829-1702-9110', + 'cardholder_name': 'b2308e2a-c1f5-469b-97b7-1f193159399b' } ], errors=[] ) ``` -**Insert call example with `continue_on_error` option** + +## Vault + +The [Vault](https://github.com/skyflowapi/skyflow-python/tree/v2/skyflow/vault) module performs operations on the vault, including inserting records, detokenizing tokens, and retrieving tokens associated with a skyflow_id. + + +### Insert data into the vault + +Apart from using the `insert` method to insert data into your vault covered in [Quickstart](#quickstart), you can also specify options in `InsertRequest`, such as returning tokenized data, upserting records, or continuing the operation in case of errors. + +#### Construct an insert request + +```python +from skyflow.error import SkyflowError +from skyflow.vault.data import InsertRequest + +""" +Example program to demonstrate inserting data into a Skyflow vault, along with corresponding InsertRequest schema. +""" + +try: + # Initialize Skyflow client + # Step 1: Prepare the data to be inserted into the Skyflow vault + insert_data = [ + # Create the first record with field names and their respective values + { + '': '', # Replace with actual field name and value + '': '', # Replace with actual field name and value + }, + # Create the second record with field names and their respective values + { + '': '', # Replace with actual field name and value + '': '', # Replace with actual field name and value + } + ] + + # Step 2: Build an InsertRequest object with the table name and the data to insert + insert_request = InsertRequest( + table_name='', # Replace with the actual table name in your Skyflow vault + values=insert_data, # Attach the data to be inserted + ) + + # Step 3: Use the Skyflow client to perform the insert operation + insert_response = skyflow_client.vault('').insert(insert_request) + # Replace with your actual vault ID + + # Print the response from the insert operation + print('Insert Response: ', insert_response) + +# Step 5: Handle any exceptions that occur during the insert operation +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes +``` + +#### Insert call example with `continue_on_error` option +The `continue_on_error` flag is a boolean that determines whether insert operation should proceed despite encountering partial errors. Set to `True` to allow the process to continue even if some errors occur. ```python from skyflow.error import SkyflowError from skyflow.vault.data import InsertRequest +""" +This example demonstrates how to insert sensitive data (e.g., card information) into a Skyflow vault using the Skyflow client. + +1. Initializes the Skyflow client. +2. Prepares a record with sensitive data (e.g., card number and cardholder name). +3. Creates an insert request for inserting the data into the Skyflow vault. +4. Specifies options to continue on error and return tokens. +5. Prints the response of the insert operation. +""" + try: + # Initialize Skyflow client + # Step 1: Initialize a list to hold the data records to be inserted into the vault insert_data = [ - {'card_number': '4111111111111111'}, - {'card_numbe': '4111111111111111'}, # Intentional typo card_numbe + # Step 2: Create the first record with card number and cardholder name + { + 'card_number': '4111111111111111', # Replace with actual card number (sensitive data) + 'cardholder_name': 'John Doe', # Replace with actual cardholder name (sensitive data) + }, + # Step 3: Create the second record with card number and cardholder name + { + 'card_number': '4111111111111111', # Ensure field name matches ("card_number") + 'cardholder_name': 'Jane Doe', # Replace with actual cardholder name (sensitive data) + } ] + # Step 4: Build the InsertRequest object with the data records to insert insert_request = InsertRequest( - table_name = 'table1', - values = insert_data, - return_tokens = True, # returns tokens - continue_on_error = True + table_name='table1', # Specify the table in the vault where the data will be inserted + values=insert_data, # Attach the data (records) to be inserted + return_tokens=True, # Specify if tokens should be returned upon successful insertion + continue_on_error=True # Specify to continue inserting records even if an error occurs for some records ) - response = client.vault('').insert(insert_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 5: Perform the insert operation using the Skyflow client + insert_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').insert(insert_request) + # Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + # Step 6: Print the response from the insert operation + print('Insert Response: ', insert_response) +except SkyflowError as error: + # Step 7: Handle any exceptions that may occur during the insert operation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes ``` Sample Response @@ -722,9 +634,11 @@ InsertResponse( inserted_fields= [ { - 'skyflow_id': '89c125d1-3bec-4360-b701-a032dda16500', + 'card_number': '5484-7829-1702-9110', 'request_index': 0, - 'card_number': '5479-4229-4622-1393' + 'skyflow_id': '9fac9201-7b8a-4446-93f8-5244e1213bd1', + 'cardholder_name': 'b2308e2a-c1f5-469b-97b7-1f193159399b', + } ], errors= @@ -738,28 +652,57 @@ InsertResponse( ``` -**Insert call example with `upsert` options** +**Insert call example with `upsert` option** +An upsert operation checks for a record based on a unique column's value. If a match exists, the record is updated; otherwise, a new record is inserted. ```python from skyflow.error import SkyflowError from skyflow.vault.data import InsertRequest +""" +This example demonstrates how to insert sensitive data (e.g., card information) into a Skyflow vault using the Skyflow client. + +1. Initializes the Skyflow client. +2. Prepares a record with sensitive data (e.g., card number and cardholder name). +3. Creates an insert request for inserting the data into the Skyflow vault. +4. Specifies the field (cardholder_name) for upsert operations. +5. Prints the response of the insert operation. +""" + try: + # Initialize Skyflow client + # Step 1: Initialize a list to hold the data records for the insert/upsert operation insert_data = [ - {"name": 'sample name'}, + # Step 2: Create a record with the field 'cardholder_name' to insert or upsert + { + 'cardholder_name': 'John Doe', # Replace with the actual cardholder name + } ] + # Step 3: Build the InsertRequest object with the upsertData insert_request = InsertRequest( - table_name = 'table1', - values = insert_data, - return_tokens = True, # returns tokens - upsert = "name" # unique column name + table_name='table1', # Specify the table in the vault where the data will be inserted + values=insert_data, # Attach the data (records) to be inserted + return_tokens=True, # Specify if tokens should be returned upon successful insertion + upsert='cardholder_name' # Specify the field to be used for upsert operations (e.g., cardholder_name) ) - response = client.vault('').insert(insert_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 4: Perform the insert/upsert operation using the Skyflow client + insert_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').insert(insert_request) + # Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + # Step 5: Print the response from the insert/upsert operation + print('Insert Response: ', insert_response) + +except SkyflowError as error: + # Step 6: Handle any exceptions that may occur during the insert/upsert operation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes ``` Skyflow returns tokens, with `upsert` support, for the record you just inserted. @@ -769,8 +712,8 @@ InsertResponse( inserted_fields= [ { - 'skyflow_id': 'a8f3ed5d-55eb-4f32-bf7e-2dbf4b9d9097', - 'name': '3f27b3d7-6bf0-432a-acf9-789c0470e2da' + 'skyflow_id': '9fac9201-7b8a-4446-93f8-5244e1213bd1', + 'name': '73ce45ce-20fd-490e-9310-c1d4f603ee83' } ], errors=[] @@ -779,27 +722,43 @@ InsertResponse( ### Detokenize -To retrieve tokens from your vault, you can use the `detokenize` method. The `DetokenizeRequest` class requires a list of detokenization data to be provided as input. Additionally, the redaction type and continue on error are optional parameters. - +To retrieve tokens from your vault, use the `detokenize` method. The `DetokenizeRequest` class requires a list of detokenization data as input. Additionally, you can provide optional parameters, such as the redaction type and the option to continue on error. +#### Construct a detokenize request ```python from skyflow.error import SkyflowError from skyflow.utils.enums import RedactionType from skyflow.vault.tokens import DetokenizeRequest - +""" +This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault, along with corresponding DetokenizeRequest schema. +""" try: - detokenize_data = ['', '', ''] + # Initialize Skyflow client + # Step 1: Step 1: Initialize a list of tokens to be detokenized (replace with actual tokens) + detokenize_data = ['', '', ''] # Replace with your actual token values + # Step 2: Create the DetokenizeRequest object with the tokens and redaction type detokenize_request = DetokenizeRequest( - tokens =d etokenize_data, - continue_on_error = False, # optional - redaction_type = RedactionType.PLAIN_TEXT # optional + tokens=detokenize_data, # Provide the list of tokens to be detokenized + continue_on_error=True, # Continue even if one token cannot be detokenized + redaction_type=RedactionType.PLAIN_TEXT # Specify how the detokenized data should be returned (plain text) ) - response = skyflow_client.vault('').detokenize(detokenize_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 3: Call the Skyflow vault to detokenize the provided tokens + detokenize_response = skyflow_client.vault('').detokenize(detokenize_request) + # Replace with your actual Skyflow vault ID + + # Step 4: Print the detokenization response, which contains the detokenized data + print('Response:', detokenize_response) +# Step 5: Handle any errors that occur during the detokenization process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the exception for debugging purposes ``` Notes: @@ -807,27 +766,49 @@ Notes: - `redaction_type` defaults to `RedactionType.PLAIN_TEXT`. - `continue_on_error` default valus is `False`. -An [example](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/detokenize_records.py) of a detokenize call: +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/detokenize_records.py) of a detokenize call ```python from skyflow.error import SkyflowError from skyflow.utils.enums import RedactionType from skyflow.vault.tokens import DetokenizeRequest - +""" +This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault. + +1. Initializes the Skyflow client. +2. Creates a list of tokens (e.g., credit card tokens) that represent the sensitive data. +3. Builds a detokenization request using the provided tokens and specifies how the redacted data should be returned. +4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data. +5. Prints the detokenization response, which contains the detokenized values or errors. +""" try: - detokenize_data = ['9738-1683-0486-1480', '6184-6357-8409-6668', '4914-9088-2814-3840'] + # Initialize Skyflow client + # Step 1: Step 1: Initialize a list of tokens to be detokenized (replace with actual tokens) + tokens = ['9738-1683-0486-1480', '6184-6357-8409-6668', '4914-9088-2814-3840'] # Replace with your actual token values + # Step 2: Create the DetokenizeRequest object with the tokens and redaction type detokenize_request = DetokenizeRequest( - tokens = detokenize_data, - continue_on_error = False, # optional - redaction_type = RedactionType.PLAIN_TEXT # optional + tokens=tokens, # Provide the list of tokens to be detokenized + continue_on_error=False, # Stop the process if any token cannot be detokenized + redaction_type=RedactionType.PLAIN_TEXT # Specify how the detokenized data should be returned (plain text) ) - response = skyflow_client.vault('').detokenize(detokenize_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 3: Call the Skyflow vault to detokenize the provided tokens + detokenize_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').detokenize(detokenize_request) + # Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + # Step 4: Print the detokenization response, which contains the detokenized data + print('Response:', detokenize_response) +# Step 5: Handle any errors that occur during the detokenization process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the exception for debugging purposes ``` Sample response: @@ -843,27 +824,49 @@ DetokenizeResponse( ) ``` -An example of a detokenize call with continue_on_error: +#### An example of a detokenize call with `continue_on_error` option: ```python from skyflow.error import SkyflowError from skyflow.utils.enums import RedactionType from skyflow.vault.tokens import DetokenizeRequest - +""" +This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault. + +1. Initializes the Skyflow client. +2. Creates a list of tokens (e.g., credit card tokens) that represent the sensitive data. +3. Builds a detokenization request using the provided tokens and specifies how the redacted data should be returned. +4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data. +5. Prints the detokenization response, which contains the detokenized values or errors. +""" try: - detokenize_data = ['9738-1683-0486-1480', '6184-6357-8409-6668', '4914-9088-2814-384'] + # Initialize Skyflow client + # Step 1: Step 1: Initialize a list of tokens to be detokenized (replace with actual tokens) + tokens = ['9738-1683-0486-1480', '6184-6357-8409-6668', '4914-9088-2814-3840'] # Replace with your actual token values + # Step 2: Create the DetokenizeRequest object with the tokens and redaction type detokenize_request = DetokenizeRequest( - tokens = detokenize_data, - continue_on_error = True, # optional - redaction_type = RedactionType.PLAIN_TEXT # optional + tokens=tokens, # Provide the list of tokens to be detokenized + continue_on_error=True, # Continue even if some tokens cannot be detokenized + redaction_type=RedactionType.PLAIN_TEXT # Specify how the detokenized data should be returned (plain text) ) - response = skyflow_client.vault('').detokenize(detokenize_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 3: Call the Skyflow vault to detokenize the provided tokens + detokenize_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').detokenize(detokenize_request) + # Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + # Step 4: Print the detokenization response, which contains the detokenized data + print('Response:', detokenize_response) +# Step 5: Handle any errors that occur during the detokenization process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the exception for debugging purposes ``` Sample response: @@ -894,39 +897,98 @@ DetokenizeResponse( ### Tokenize -To tokenize data, use the `tokenize` method. The `TokenizeRequest` class is utilized to create a tokenize request. In this request, you specify the `values` parameter, which is a list of dictionaries. Each dictionary contains two keys: `value` and `column_group`. +Tokenization replaces sensitive data with unique identifier tokens. This approach protects sensitive information by securely storing the original data while allowing the use of tokens within your application. + +To tokenize data, use the `tokenize` method. The `TokenizeRequest` class creates a tokenize request. In this request, you specify the values parameter, which is a list of column values objects. Each column value contains two properties: `value` and `column_group`. + +#### Construct a tokenize request ```python +from skyflow.error import SkyflowError from skyflow.vault.tokens import TokenizeRequest -tokenize_request = TokenizeRequest( - values = [{ - 'value': '', - 'column_group': '' - }] -) -``` +""" +This example demonstrates how to tokenize sensitive data (e.g., credit card information) using the Skyflow client, along with corresponding TokenizeRequest schema. +""" +try: + # Initialize Skyflow client + # Step 1: Initialize a list of column values to be tokenized (replace with actual sensitive data) + column_values = [ + # Step 2: Create column values for each sensitive data field (e.g., card number and cardholder name) + {"value": "", "column_group": ""}, # Replace and with actual data + {"value": "", "column_group": ""} # Replace and with actual data + ] + + # Step 3: Build the TokenizeRequest with the column values + tokenize_request = TokenizeRequest( + values=column_values + ) -Sample usage + # Step 4: Call the Skyflow vault to tokenize the sensitive data + tokenize_response = skyflow_client.vault('').tokenize(tokenize_request) + # Replace with your actual Skyflow vault ID + + # Step 5: Print the tokenization response, which contains the generated tokens or errors + print(tokenize_response) + +# Step 6: Handle any errors that occur during the tokenization process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes +``` -An [example](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/tokenize_records.py) of a tokenize call: +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/tokenize_records.py) of Tokenize call ```python from skyflow.error import SkyflowError from skyflow.vault.tokens import TokenizeRequest +""" +This example demonstrates how to tokenize sensitive data (e.g., credit card information) using the Skyflow client. + +1. Initializes the Skyflow client. +2. Creates a column value for sensitive data (e.g., credit card number). +3. Builds a tokenize request with the column value to be tokenized. +4. Sends the request to the Skyflow vault for tokenization. +5. Prints the tokenization response, which includes the token or errors. +""" try: + # Initialize Skyflow client + # Step 1: Initialize a list of column values to be tokenized (replace with actual sensitive data) + column_values = [ + # Step 2: Create column values for each sensitive data field (e.g., card number and cardholder name) + {"value": "4111111111111111", "column_group": "card_number_cg"}, # Replace and with actual data + ] + + # Step 3: Build the TokenizeRequest with the column values tokenize_request = TokenizeRequest( - values = [{ - "value": '4111111111111111', - "column_group": "card_number_cg" - }] + values=column_values ) - response = client.vault('').tokenize(tokenize_request) - print(response) -except SyntaxError as e: - print('Error Occurred: ', e) + # Step 4: Call the Skyflow vault to tokenize the sensitive data + tokenize_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').tokenize(tokenize_request) + # Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + # Step 5: Print the tokenization response, which contains the generated tokens or errors + print(tokenize_response) + +# Step 6: Handle any errors that occur during the tokenization process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes + ``` Sample response: @@ -944,58 +1006,131 @@ TokenizeResponse( ### Get -To retrieve data using Skyflow IDs or unique column values, use the `get` method. The `GetRequest` class is used to create a get request, where you specify parameters such as the table name, redaction type, Skyflow IDs, column names, column values, and return tokens. If Skyflow IDs are provided, column names and column values cannot be used. Similarly, if column names or column values are provided, Skyflow IDs cannot be used. +To retrieve data using Skyflow IDs or unique column values, use the get method. The `GetRequest` class creates a get request, where you specify parameters such as the table name, redaction type, Skyflow IDs, column names, column values, and whether to return tokens. If you specify Skyflow IDs, you can't use column names and column values, and the inverse is true—if you specify column names and column values, you can't use Skyflow IDs. + +#### Construct a get request ```python from skyflow.error import SkyflowError from skyflow.utils.enums import RedactionType from skyflow.vault.data import GetRequest -GetRequest( - table = '', - ids = ['SKYFLOW_ID1>', 'SKYFLOW_ID2>'], - return_tokens = True, - redaction_type = RedactionType.PLAIN_TEXT -) +""" +This example demonstrates how to retrieve data from the Skyflow vault using different methods, along with corresponding GetRequest schema. +""" +try: + # Initialize Skyflow client + # Step 1: Initialize a list of Skyflow IDs to retrieve records (replace with actual Skyflow IDs) + ids = ['', ''] # Replace with actual Skyflow IDs + + # Step 2: Create a GetRequest to retrieve records by Skyflow ID without returning tokens + get_by_id_request = GetRequest( + table='', # Replace with your actual table name + ids=ids, + return_tokens=False, # Set to false to avoid returning tokens + redaction_type=RedactionType.PLAIN_TEXT # Redact data as plain text + ) -# or + # Send the request to the Skyflow vault and retrieve the records + get_by_id_response = skyflow_client.vault('').get(get_by_id_request) + # Replace with your actual Skyflow vault ID + + print(get_by_id_response) + + # Step 3: Create another GetRequest to retrieve records by Skyflow ID with tokenized values + get_tokens_request = GetRequest( + table='', # Replace with your actual table name + ids=ids, + return_tokens=True # Set to True to return tokenized values + ) + + # Send the request to the Skyflow vault and retrieve the tokenized records + get_tokens_response = skyflow_client.vault('').get(get_tokens_request) + print(get_tokens_response) + + column_values = [ + '', # Replace with the actual column value + '' # Replace with the actual column value + ] + + # Step 4: Create a GetRequest to retrieve records based on specific column values + get_by_column_request = GetRequest( + table='', # Replace with the actual table name + column_name='', # Replace with the column name + column_values=column_values, # Add the list of column values to filter by + redaction_type=RedactionType.PLAIN_TEXT # Redact data as plain text + ) + + # Send the request to the Skyflow vault and retrieve the filtered records + get_by_column_response = skyflow_client.vault('').get(get_by_column_request) + print(get_by_column_response) +# Step 5: Handle any errors that occur during the retrieval process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes -GetRequest( - table = '', - column_name ='', - column_values = ['COLUMN_VALUE1>', 'COLUMN_VALUE2>'], - redaction_type = RedactionType.PLAIN_TEXT -) ``` -Sample usage +#### Get by skyflow IDs +Retrieve specific records using skyflow `ids`. Ideal for fetching exact records when IDs are known. -### Get By Column Name and Column Values -The following snippet shows how to use the `get` method using column names and column values. For details, see [get_column_values.py](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/get_column_values.py), +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/get_records.py) of a get call to retrieve data using Redaction type: ```python from skyflow.error import SkyflowError from skyflow.utils.enums import RedactionType from skyflow.vault.data import GetRequest -try: - column_values = [ - '123456' - ] +""" +This example demonstrates how to retrieve data from the Skyflow vault using a list of Skyflow IDs. - get_request = GetRequest( - table = 'table1', - column_name = 'card_number', # It must be configured as unique in the schema. - column_values = column_values, - redaction_type = RedactionType.PLAIN_TEXT +1. Initializes the Skyflow client with a given vault ID. +2. Creates a request to retrieve records based on Skyflow IDs. +3. Specifies that the response should not return tokens. +4. Uses plain text redaction type for the retrieved records. +5. Prints the response to display the retrieved records. +""" +try: + # Initialize Skyflow client + # Step 1: Initialize a list of Skyflow IDs to retrieve records (replace with actual Skyflow IDs) + ids = ['a581d205-1969-4350-acbe-a2a13eb871a6', '5ff887c3-b334-4294-9acc-70e78ae5164a'] # Replace with actual Skyflow IDs + + # Step 2: Create a GetRequest to retrieve records by Skyflow ID without returning tokens + # The request specifies: + # - `ids`: The list of Skyflow IDs to retrieve + # - `table`: The table from which the records will be retrieved + # - `return_tokens`: Set to false, meaning tokens will not be returned in the response + # - `redaction_type`: Set to PLAIN_TEXT, meaning the retrieved records will have data redacted as plain text + get_by_id_request = GetRequest( + table='table1', # Replace with the actual table name + ids=ids, + return_tokens=False, # Set to false to avoid returning tokens + redaction_type=RedactionType.PLAIN_TEXT # Redact data as plain text ) - response = skyflow_client.vault('').get(get_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 3: Send the request to the Skyflow vault and retrieve the records + get_by_id_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').get(get_by_id_request) + # Replace with actual Vault ID + print(get_by_id_response) # Print the response to the console + +# Step 5: Handle any errors that occur during the retrieval process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes ``` Sample response: @@ -1004,57 +1139,72 @@ Sample response: GetResponse( data=[ { - 'card_number': '123456', - 'skyflow_id': '4f7af9f9-09e0-4f47-af8e-04c9b1ee1968' + 'card_number': '4555555555555553', + 'email': 'john.doe@gmail.com', + 'name': 'john doe', + 'skyflow_id': 'a581d205-1969-4350-acbe-a2a13eb871a6' + }, + { + 'card_number': '4555555555555559', + 'email': 'jane.doe@gmail.com', + 'name': 'jane doe', + 'skyflow_id': '5ff887c3-b334-4294-9acc-70e78ae5164a' } ], errors=[] ) - -``` - -### Get By Skyflow Ids - -```python -from skyflow.error import SkyflowError -from skyflow.utils.enums import RedactionType -from skyflow.vault.data import GetRequest - -GetRequest( - table = '', - ids = ['SKYFLOW_ID1>', 'SKYFLOW_ID2>'], - return_tokens = True, - redaction_type = RedactionType.PLAIN_TEXT -) ``` -#### Redaction Types - -There are 4 accepted values in Skyflow.RedactionTypes: +#### Get tokens +Return tokens for records. Ideal for securely processing sensitive data while maintaining data privacy. -- `PLAIN_TEXT` -- `MASKED` -- `REDACTED` -- `DEFAULT` +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/get_records.py) of get call to retrieve tokens using Skyflow IDs: -An [example](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/get_records.py) of get by skyflow ids call: ```python from skyflow.error import SkyflowError from skyflow.utils.enums import RedactionType from skyflow.vault.data import GetRequest +""" +This example demonstrates how to retrieve data from the Skyflow vault and return tokens along with the records. + +1. Initializes the Skyflow client with a given vault ID. +2. Creates a request to retrieve records based on Skyflow IDs and ensures tokens are returned. +3. Prints the response to display the retrieved records along with the tokens. +""" try: - get_request = GetRequest( - table = 'table1', - ids = ['aea64577-12b1-4682-aad5-a183194c3f3d', 'b385c565-86eb-4af2-b959-8376f9b0754b'], - redaction_type = RedactionType.PLAIN_TEXT + # Initialize Skyflow client + # Step 1: Initialize a list of Skyflow IDs (replace with actual Skyflow IDs) + ids = ['a581d205-1969-4350-acbe-a2a13eb871a6', '5ff887c3-b334-4294-9acc-70e78ae5164a'] # Replace with actual Skyflow IDs + + # Step 2: Create a GetRequest to retrieve records based on Skyflow IDs + # The request specifies: + # - `ids`: The list of Skyflow IDs to retrieve + # - `table`: The table from which the records will be retrieved + # - `return_tokens`: Set to false, meaning tokens will not be returned in the response + get_tokens_request = GetRequest( + table='table1', # Replace with the actual table name + ids=ids, + return_tokens=True, # Set to false to avoid returning tokens ) - response = client.vault('').get(get_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 3: Send the request to the Skyflow vault and retrieve the records + get_tokens_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').get(get_tokens_request) + # Replace with actual Vault ID + + print(get_tokens_response) # Print the response to the console + +# Step 5: Handle any errors that occur during the retrieval process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes ``` Sample response: @@ -1063,36 +1213,75 @@ Sample response: GetResponse( data=[ { - 'card_number': '4555555555555553', - 'skyflow_id': 'aea64577-12b1-4682-aad5-a183194c3f3d' + 'card_number': '3998-2139-0328-0697', + 'email': 'c9a6c9555060@82c092e7.bd52', + 'name': '82c092e7-74c0-4e60-bd52-c9a6c9555060', + 'skyflow_id': 'a581d205-1969-4350-acbe-a2a13eb871a6' }, { - 'card_number': '4555555555555559', - 'skyflow_id': 'b385c565-86eb-4af2-b959-8376f9b0754b' + 'card_number': '3562-0140-8820-7499', + 'email': '6174366e2bc6@59f82e89.93fc', + 'name': '59f82e89-138e-4f9b-93fc-6174366e2bc6', + 'skyflow_id': '5ff887c3-b334-4294-9acc-70e78ae5164a' } ], errors=[] ) - ``` -The following snippet shows how to use the `get()` method with return_tokens true. +#### Get by column name and column values +Retrieve records by unique column values. Ideal for querying data without knowing Skyflow IDs, using alternate unique identifiers. + +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/get_column_values.py) of get call to retrieve data using column name and column values: ```python from skyflow.error import SkyflowError +from skyflow.utils.enums import RedactionType from skyflow.vault.data import GetRequest +""" +This example demonstrates how to retrieve data from the Skyflow vault based on column values. + +1. Initializes the Skyflow client with a given vault ID. +2. Creates a request to retrieve records based on specific column values (e.g., email addresses). +3. Prints the response to display the retrieved records after redacting sensitive data based on the specified redaction type. +""" try: - get_request = GetRequest( - table = 'table1', - ids = ['aea64577-12b1-4682-aad5-a183194c3f3d', 'b385c565-86eb-4af2-b959-8376f9b0754b'], - return_tokens = True + # Initialize Skyflow client + # Step 1: Initialize a list of column values (email addresses in this case) + column_values = [ + 'john.doe@gmail.com', # Example email address + 'jane.doe@gmail.com' # Example email address + ] + + # Step 2: Step 2: Create a GetRequest to retrieve records based on column values + # The request specifies: + # - `ids`: The list of Skyflow IDs to retrieve + # - `table`: The table from which the records will be retrieved + # - `return_tokens`: Set to false, meaning tokens will not be returned in the response + get_by_column_request = GetRequest( + table='table1', # Replace with the actual table name + column_name='email', # The column name to filter by (e.g., "email") + column_values=column_values, # The list of column values to match + redaction_type=RedactionType.PLAIN_TEXT # Set the redaction type (e.g., PLAIN_TEXT) ) - response = client.vault('').get(get_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 3: Send the request to the Skyflow vault and retrieve the records + get_by_column_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').get(get_by_column_request) + # Replace with actual Vault ID + + print(get_by_column_response) # Print the response to the console + +# Step 5: Handle any errors that occur during the retrieval process +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes ``` @@ -1102,76 +1291,164 @@ Sample response: GetResponse( data=[ { - 'card_number': '3562-0140-8820-7499', - 'skyflow_id': 'aea64577-12b1-4682-aad5-a183194c3f3d' + 'card_number': '4555555555555553', + 'email': 'john.doe@gmail.com', + 'name': 'john doe', + 'skyflow_id': 'a581d205-1969-4350-acbe-a2a13eb871a6' }, { - 'card_number': '3998-2139-0328-0697', - 'skyflow_id': 'b385c565-86eb-4af2-b959-8376f9b0754b' + 'card_number': '4555555555555559', + 'email': 'jane.doe@gmail.com', + 'name': 'jane doe', + 'skyflow_id': '5ff887c3-b334-4294-9acc-70e78ae5164a' } ], errors=[] ) ``` +#### Redaction Types +Redaction types determine how sensitive data is displayed when retrieved from the vault. + +**Available Redaction Types** + +- `DEFAULT`: Applies the vault-configured default redaction setting. +- `DEFAULT`: Completely removes sensitive data from view. +- `MASKED`: Partially obscures sensitive information. +- `PLAIN_TEXT`: Displays the full, unmasked data. + +**Choosing the Right Redaction Type** +- Use `REDACTED` for scenarios requiring maximum data protection to prevent exposure of sensitive information. +- Use `MASKED` to provide partial visibility of sensitive data for less critical use cases. +- Use `PLAIN_TEXT` for internal, authorized access where full data visibility is necessary. + ### Update To update data in your vault, use the `update` method. The `UpdateRequest` class is used to create an update request, where you specify parameters such as the table name, data (as a dictionary), tokens, return_tokens, and token_strict. If `return_tokens` is set to True, Skyflow returns tokens for the updated records. If `return_tokens` is set to False, Skyflow returns IDs for the updated records. +#### Construct an update request + ```python from skyflow.error import SkyflowError +from skyflow.utils.enums import TokenMode from skyflow.vault.data import UpdateRequest +""" +This example demonstrates how to update records in the Skyflow vault by providing new data and/or tokenized values, along with the corresponding UpdateRequest schema. +""" + try: + # Initialize Skyflow client + # Step 1: Prepare the data to update in the vault + # Use a dictionary to store the data that will be updated in the specified table update_data = { - 'skyflow_id': '', - '': '' + 'skyflow_id': '', # Skyflow ID for identifying the record to update + '': '', # Example of a column name and its value to update + '': '' # Another example of a column name and its value to update + } + + # Step 2: Prepare the tokens (if necessary) for certain columns that require tokenization + # Use a dictionary to specify columns that need tokens in the update request + tokens = { + '': '' # Example of a column name that should be tokenized } + # Step 3: Create an UpdateRequest to specify the update operation + # The request includes the table name, data, tokens, and the returnTokens flag update_request = UpdateRequest( - table='TABLE_NAME', - data=update_data + table='', # Replace with the actual table name to update + token_mode=TokenMode.ENABLE, # Specifies the tokenization mode (ENABLE means tokenization is applied) + data=update_data, # The data to update in the record + tokens=tokens, # The tokens associated with specific columns + return_tokens=True # Specify whether to return tokens in the response ) - response = skyflow_client.vault('VAULT_ID').update(update_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) -``` + # Step 4: Send the request to the Skyflow vault and update the record + update_response = skyflow_client.vault('').update(update_request) # Replace with actual Vault ID + + # Step 5: Print the response to confirm the update result + print(update_response) + +except SkyflowError as error: + # Step 6: Handle any errors that occur during the update operation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) -Sample usage +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes +``` -The following snippet shows how to use the `update()` method. For details, see [update_record.py](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/update_record.py), +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/update_record.py) of update call ```python from skyflow.error import SkyflowError +from skyflow.utils.enums import TokenMode from skyflow.vault.data import UpdateRequest +""" +This example demonstrates how to update a record in the Skyflow vault with specified data and tokens. + +1. Initializes the Skyflow client with a given vault ID. +2. Constructs an update request with data to modify and tokens to include. +3. Sends the request to update the record in the vault. +4. Prints the response to confirm the success or failure of the update operation. +""" + try: + # Initialize Skyflow client + # Step 1: Prepare the data to update in the vault + # Use a dictionary to store the data that will be updated in the specified table update_data = { - 'skyflow_id': '3b80c76a-c0d7-4c02-be00-b4128cb0f315', - 'card_number': '4111111111117777' + 'skyflow_id': '5b699e2c-4301-4f9f-bcff-0a8fd3057413', # Skyflow ID for identifying the record to update + 'name': 'john doe', # Example of a column name and its value to update + 'card_number': '4111111111111115' # Another example of a column name and its value to update } + # Step 2: Prepare the tokens (if necessary) for certain columns that require tokenization + # Use a dictionary to specify columns that need tokens in the update request + tokens = { + 'name': '72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a' # Example of a column name that should be tokenized + } + + # Step 3: Create an UpdateRequest to specify the update operation + # The request includes the table name, data, tokens, and the returnTokens flag update_request = UpdateRequest( - table = 'table1', - data = update_data + table='table1', # Replace with the actual table name to update + token_mode=TokenMode.ENABLE, # Token mode enabled to allow tokenization of sensitive data + data=update_data, # The data to update in the record + tokens=tokens, # The tokenized values for sensitive columns ) - response = skyflow_client.vault('').update(update_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) + # Step 4: Send the request to the Skyflow vault and update the record + update_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').update(update_request) # Replace with actual Vault ID + + # Step 5: Print the response to confirm the update result + print(update_response) + +except SkyflowError as error: + # Step 6: Handle any errors that occur during the update operation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes ``` Sample response -`return_tokens` set to `True` +- When `return_tokens` is set to `True` ```python UpdateResponse( updated_field={ - 'skyflow_id': '3b80c76a-c0d7-4c02-be00-b4128cb0f315', + 'skyflow_id': '5b699e2c-4301-4f9f-bcff-0a8fd3057413', + 'name': '72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a', 'card_number': '4131-1751-0217-8491' }, errors=[] @@ -1179,11 +1456,11 @@ UpdateResponse( ``` -`return_tokens` set to `False` +- When `return_tokens` is set to `False` ```python UpdateResponse( - updated_field={'skyflow_id': '3b80c76a-c0d7-4c02-be00-b4128cb0f315'}, + updated_field={'skyflow_id': '5b699e2c-4301-4f9f-bcff-0a8fd3057413'}, errors=[] ) @@ -1193,44 +1470,84 @@ UpdateResponse( To delete records using Skyflow IDs, use the `delete` method. The `DeleteRequest` class accepts a list of Skyflow IDs that you want to delete, as shown below: +#### Construct a delete request + ```python from skyflow.error import SkyflowError from skyflow.vault.data import DeleteRequest -primary_delete_ids = [ - 'SKYFLOW_ID1', - 'SKYFLOW_ID2', - 'SKYFLOW_ID3', -] +""" +This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs, along with corresponding DeleteRequest schema. +""" -delete_request = DeleteRequest( - table = '', - ids = primary_delete_ids -) +try: + # Initialize Skyflow client + # Step 1: Prepare a list of Skyflow IDs for the records to delete + # The list stores the Skyflow IDs of the records that need to be deleted from the vault + delete_ids = ['', '', ''] # Replace with actual Skyflow IDs + + # Step 2: Create a DeleteRequest to define the delete operation + # The request specifies the table from which to delete the records and the IDs of the records to delete + delete_request = DeleteRequest( + table='', # Replace with the actual table name from which to delete + ids=delete_ids # List of Skyflow IDs to delete + ) + + # Step 3: Send the delete request to the Skyflow vault + delete_response = skyflow_client.vault('').delete(delete_request) # Replace with your actual Vault ID + print(delete_response) # Print the response to confirm the delete result + +except SkyflowError as error: + # Step 4: Handle any exceptions that occur during the delete operation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the exception stack trace for debugging purposes ``` -An [example](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/delete_records.py) of delete call: +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/delete_records.py) of delete call ```python from skyflow.error import SkyflowError from skyflow.vault.data import DeleteRequest +""" +This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs. + +1. Initializes the Skyflow client with a given Vault ID. +2. Constructs a delete request by specifying the IDs of the records to delete. +3. Sends the delete request to the Skyflow vault to delete the specified records. +4. Prints the response to confirm the success or failure of the delete operation. +""" + try: - delete_ids = [ - '77e093f8-3ace-4295-8683-bb6745d6178e', - 'bf5989cc-79e8-4b2f-ad71-cb20b0a76091' - ] + # Initialize Skyflow client + # Step 1: Prepare a list of Skyflow IDs for the records to delete + # The list stores the Skyflow IDs of the records that need to be deleted from the vault + delete_ids = ['9cbf66df-6357-48f3-b77b-0f1acbb69280', 'ea74bef4-f27e-46fe-b6a0-a28e91b4477b', '47700796-6d3b-4b54-9153-3973e281cafb'] # Replace with actual Skyflow IDs + # Step 2: Create a DeleteRequest to define the delete operation + # The request specifies the table from which to delete the records and the IDs of the records to delete delete_request = DeleteRequest( - table='table1', - ids=delete_ids + table='table1', # Replace with the actual table name from which to delete + ids=delete_ids # List of Skyflow IDs to delete ) - response = client.vault('').delete(delete_request) - print('Response:', response) -except SkyflowError as e: - print('Error Occurred:', e) - + # Step 3: Send the delete request to the Skyflow vault + delete_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').delete(delete_request) # Replace with your actual Vault ID + print(delete_response) # Print the response to confirm the delete result +# Step 4: Handle any exceptions that occur during the delete operation +except SkyflowError as error: + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + print('Unexpected Error:', error) # Print the exception stack trace for debugging purposes ``` Sample response: @@ -1238,46 +1555,199 @@ Sample response: ```python DeleteResponse( deleted_ids=[ - '77e093f8-3ace-4295-8683-bb6745d6178e', - 'bf5989cc-79e8-4b2f-ad71-cb20b0a76091' + '9cbf66df-6357-48f3-b77b-0f1acbb69280', + 'ea74bef4-f27e-46fe-b6a0-a28e91b4477b', + '47700796-6d3b-4b54-9153-3973e281cafb' ], errors=[] ) ``` -### Invoke Connection +### Query + +To retrieve data with SQL queries, use the `query` method. `QueryRequest` is class that takes the `query` parameter as follows: -Using Skyflow Connection, end-user applications can integrate checkout/card issuance flow with their apps/systems. To invoke connection, use the `invoke` method of the Skyflow client. +#### Construct a query request +Refer to [Query your data](https://docs.skyflow.com/query-data/) and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on supported SQL statements, operators, and keywords. ```python from skyflow.error import SkyflowError -from skyflow.vault.connection import InvokeConnectionRequest +from skyflow.vault.data import QueryRequest -body = { - 'KEY1': 'VALUE1', - 'KEY2': 'VALUE2' -} -headers = { - 'KEY1': 'VALUE1' -} -path_params = { - 'KEY1': 'VALUE1' -} -query_params = { - 'KEY1': 'VALUE1' -} +""" +This example demonstrates how to execute a custom SQL query on a Skyflow vault, along with QueryRequest schema. +""" + +try: + # Initialize Skyflow client + # Step 1: Define the SQL query to execute on the Skyflow vault + # Replace "" with the actual SQL query you want to run + query = '' # Example: "SELECT * FROM table1 WHERE column1 = 'value'" + + # Step 2: Create a QueryRequest with the specified SQL query + query_request = QueryRequest( + query=query # SQL query to execute + ) + + # Step 3: Execute the query request on the specified Skyflow vault + query_response = skyflow_client.vault('').query(query_request) # Replace with your actual Vault ID + + # Step 4: Print the response containing the query results + print('Query Result:', query_response) + +except SkyflowError as error: + # Step 5: Handle any exceptions that occur during the query execution + print('Skyflow Specific Error:', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + # Handle any unexpected errors during execution + print('Unexpected Error:', error) # Print the stack trace for debugging purposes +``` +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/query_records.py) of query call -invoke_connection_request = InvokeConnectionRequest( - method = Method.POST, - body = body, - headers = headers, # optional - path_params = path_params, # optional - query_params = query_params # optional +```python +from skyflow.error import SkyflowError +from skyflow.vault.data import QueryRequest + +""" +This example demonstrates how to execute a SQL query on a Skyflow vault to retrieve data. + +1. Initializes the Skyflow client with the Vault ID. +2. Constructs a query request with a specified SQL query. +3. Executes the query against the Skyflow vault. +4. Prints the response from the query execution. +""" + +try: + # Initialize Skyflow client + # Step 1: Define the SQL query + # Example query: Retrieve all records from the "cards" table with a specific skyflow_id + query = "SELECT * FROM cards WHERE skyflow_id='3ea3861-x107-40w8-la98-106sp08ea83f'" # Example: "SELECT * FROM table1 WHERE column1 = 'value'" + + # Step 2: Create a QueryRequest with the SQL query + query_request = QueryRequest( + query=query # SQL query to execute + ) + + # Step 3: Execute the query request on the specified Skyflow vault + query_response = skyflow_client.vault('9f27764a10f7946fe56b3258e117').query(query_request) # Vault ID: 9f27764a10f7946fe56b3258e117 + + # Step 4: Print the response containing the query results + print(query_response) + +except SkyflowError as error: + # Step 5: Handle any exceptions that occur during the query execution + print('Skyflow Specific Error:', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) + +except Exception as error: + print('Unexpected Error:', error) # Print the stack trace for debugging purposes +``` + +Sample Response + +```python +QueryResponse( + fields=[ + { + 'card_number': 'XXXXXXXXXXXX1112', + 'name': 'S***ar', + 'skyflow_id': '3ea3861-x107-40w8-la98-106sp08ea83f', + 'tokenized_data': {} + } + ], + errors=[] ) ``` -`methodName` supports the following methods: +### Connections + +Skyflow Connections is a gateway service that uses tokenization to securely send and receive data between your systems and first- or third-party services. The [connections](https://github.com/skyflowapi/skyflow-python/tree/v2/skyflow/vault/connection) module invokes both inbound and/or outbound connections. +- **Inbound connections**: Act as intermediaries between your client and server, tokenizing sensitive data before it reaches your backend, ensuring downstream services handle only tokenized data. +- **Outbound connections**: Enable secure extraction of data from the vault and transfer it to third-party services via your backend server, such as processing checkout or card issuance flows. + +#### Invoke a connection +To invoke a connection, use the `invoke` method of the Skyflow client. +#### Construct an invoke connection request + +```python +from skyflow.error import SkyflowError +from skyflow.utils.enums import RequestMethod +from skyflow.vault.connection import InvokeConnectionRequest + +""" +This example demonstrates how to invoke an external connection using the Skyflow SDK, along with corresponding InvokeConnectionRequest schema. +""" + +try: + # Initialize Skyflow client + # Step 1: Define the request body parameters + # These are the values you want to send in the request body + request_body = { + '': '', + '': '' + } + + # Step 2: Define the request headers + # Add any required headers that need to be sent with the request + request_headers = { + '': '', + '': '', + } + + # Step 3: Define the path parameters + # Path parameters are part of the URL and typically used in RESTful APIs + path_params = { + '': '', + '': '' + } + + # Step 4: Define the query parameters + # Query parameters are included in the URL after a '?' and are used to filter or modify the response + query_params = { + '': '', + '': '', + } + + # Step 5: Build the InvokeConnectionRequest using the provided parameters + invoke_connection_request = InvokeConnectionRequest( + method=RequestMethod.POST, # The HTTP method to use for the request (POST in this case) + body=request_body, # The body of the request + headers=request_headers, # The headers to include in the request + path_params=path_params, # The path parameters for the URL + query_params=query_params # The query parameters to append to the URL + ) + + # Step 6: Invoke the connection using the request + # Replace '' with the actual connection ID you are using + response = skyflow_client.connection('').invoke(invoke_connection_request) + + # Step 7: Print the response from the invoked connection + # This response contains the result of the request sent to the external system + print('Connection invocation successful: ', response) + +except SkyflowError as error: + # Step 8: Handle any exceptions that occur during the connection invocation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + # Print the exception stack trace for debugging + print('Unexpected Error:', error) + +``` + +`method` supports the following methods: - GET - POST @@ -1285,47 +1755,86 @@ invoke_connection_request = InvokeConnectionRequest( - PATCH - DELETE -**path_params, query_params, request_header, request_body** are the JSON objects represented as dictionaries that will be sent through the connection integration url. +**path_params, query_params, header, body** are the JSON objects represented as dictionaries that will be sent through the connection integration url. -An [example](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/invoke_connection.py) of invoke_connection: +#### An [example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/vault_api/invoke_connection.py) of Invoke Connection ```python -from skyflow import Skyflow -from skyflow import LogLevel -from skyflow.utils.enums import Method +from skyflow import Skyflow, LogLevel from skyflow.error import SkyflowError +from skyflow.utils.enums import RequestMethod from skyflow.vault.connection import InvokeConnectionRequest -credentials = { - 'path': '/path/to/credentials.json', -} +""" +This example demonstrates how to invoke an external connection using the Skyflow SDK. +It configures a connection, sets up the request, and sends a POST request to the external service. -client = ( - Skyflow.builder() - .add_connection_config({ - 'connection_id': '', - 'connection_url': '', - 'credentials': credentials - }) - .set_log_level(LogLevel.OFF) - .build() -) +1. Initialize Skyflow client with connection details. +2. Define the request body, headers, and method. +3. Execute the connection request. +4. Print the response from the invoked connection. +""" -invoke_connection_request = InvokeConnectionRequest( - method=Method.POST, - body={ - 'card_number': '4337-1696-5866-0865', - 'ssn': '524-41-4248' - }, - headers = { - 'Content-Type': 'application/json' +try: + # Initialize Skyflow client + # Step 1: Set up credentials and connection configuration + # Load credentials from a JSON file (you need to provide the correct path) + credentials = { + 'path': '/path/to/credentials.json' } -) -response = client.connection('').invoke(invoke_connection_request) + # Define the connection configuration (URL and credentials) + connection_config = { + 'connection_id': '', # Replace with actual connection ID + 'connection_url': 'https://connection.url.com', # Replace with actual connection URL + 'credentials': credentials # Set credentials for the connection + } -print(response) + # Initialize the Skyflow client with the connection configuration + skyflow_client = ( + Skyflow.builder() + .add_connection_config(connection_config) # Add connection configuration to client + .set_log_level(LogLevel.DEBUG) # Set log level to DEBUG for detailed logs + .build() # Build the Skyflow client instance + ) + # Step 2: Define the request body and headers + request_body = { + 'card_number': '4337-1696-5866-0865', # Example card number + 'ssn': '524-41-4248' # Example SSN + } + + # Add any required headers that need to be sent with the request + request_headers = { + 'Content-Type': 'application/json', # Set content type for the request + } + + # Step 3: Build the InvokeConnectionRequest with required parameters + # Set HTTP method to POST, include the request body and headers + invoke_connection_request = InvokeConnectionRequest( + method=RequestMethod.POST, # The HTTP method to use for the request (POST in this case) + body=request_body, # The body of the request + headers=request_headers, # The headers to include in the request + ) + + # Step 4: Invoke the connection using the request + # Replace '' with the actual connection ID you are using + response = skyflow_client.connection('').invoke(invoke_connection_request) + + # Step 5: Print the response from the invoked connection + # This response contains the result of the request sent to the external system + print('Connection invocation successful: ', response) + +except SkyflowError as error: + # Step 6: Handle any exceptions that occur during the connection invocation + print('Skyflow Specific Error: ', { + 'code': error.http_code, + 'message': error.message, + 'details': error.details + }) +except Exception as error: + # Print the exception stack trace for debugging + print('Unexpected Error:', error) ``` Sample response: @@ -1335,126 +1844,376 @@ ConnectionResponse( { 'card_number': '4337-1696-5866-0865', 'ssn': '524-41-4248', - 'request_id': '84796a11-0b7d-4cb0-a348-cf9fefb5886f,84796a11-0b7d-4cb0-a348-cf9fefb5886f' + 'request_id': '4a3453b5-7aa4-4373-98d7-cf102b1f6f97' } ) ``` -### Query +### Authenticate with bearer tokens +This section covers methods for generating and managing tokens to authenticate API calls: -To retrieve data with SQL queries, use the `query` method. `QueryRequest` is class that takes the `query` parameter as follows: +- **Generate a bearer token:** +Enable the creation of bearer tokens using service account credentials. These tokens, valid for 60 minutes, provide secure access to Vault services and management APIs based on the service account's permissions. Use this for general API calls when you only need basic authentication without additional context or role-based restrictions. +- **Generate a bearer token with context:** +Support embedding context values into bearer tokens, enabling dynamic access control and the ability to track end-user identity. These tokens include context claims and allow flexible authorization for Vault services. Use this when policies depend on specific contextual attributes or when tracking end-user identity is required. +- **Generate a scoped bearer token:** +Facilitate the creation of bearer tokens with role-specific access, ensuring permissions are limited to the operations allowed by the designated role. This is particularly useful for service accounts with multiple roles. Use this to enforce fine-grained role-based access control, ensuring tokens only grant permissions for a specific role. +- **Generate signed data tokens:** +Add an extra layer of security by digitally signing data tokens with the service account's private key. These signed tokens can be securely detokenized, provided the necessary bearer token and permissions are available. Use this to add cryptographic protection to sensitive data, enabling secure detokenization with verified integrity and authenticity. -```python -from skyflow.vault.data import QueryRequest +#### Generate a bearer token +The [Service Account](https://github.com/skyflowapi/skyflow-python/tree/v2/skyflow/service_account) Python package generates service account tokens using a service account credentials file, which is provided when a service account is created. The tokens generated by this module are valid for 60 minutes and can be used to make API calls to the [Data](https://docs.skyflow.com/record/) and [Management](https://docs.skyflow.com/management/) APIs, depending on the permissions assigned to the service account. -query_request = QueryRequest( - query= '' -) -``` - -See [Query your data](https://docs.skyflow.com/query-data/) and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on supported SQL statements, operators, and keywords. +The `generate_bearer_token(filepath)` function takes the credentials file path for token generation, alternatively, you can also send the entire credentials as string, by using `generate_bearer_token_from_creds(credentials)` -An [example](https://github.com/skyflowapi/skyflow-python/blob/SK-1749-readme/samples/vault_api/query_records.py) of Query call: +#### [Example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/service_account/token_generation_example.py): ```python +import json from skyflow.error import SkyflowError -from skyflow.vault.data import QueryRequest - -query_request = QueryRequest( - query = "SELECT * FROM cards WHERE skyflow_id='3ea3861-x107-40w8-la98-106sp08ea83f'" +from skyflow.service_account import ( + generate_bearer_token, + generate_bearer_token_from_creds, + is_expired, ) +# Example program to generate a Bearer Token using Skyflow's service account utilities. +# The token can be generated in two ways: +# 1. Using the file path to a credentials.json file. +# 2. Using the JSON content of the credentials file as a string. + +# Variable to store the generated token +bearer_token = '' + +# Example 1: Generate Bearer Token using a credentials.json file +try: + # Specify the full file path to the credentials.json file + file_path = 'CREDENTIALS_FILE_PATH' + + # Check if the token is already generated and still valid + if not is_expired(bearer_token): + print("Generated Bearer Token (from file):", bearer_token) + else: + # Generate a new Bearer Token from the credentials file + token, _ = generate_bearer_token(file_path) # Set credentials from the file path + bearer_token = token + # Print the generated Bearer Token to the console + print("Generated Bearer Token (from file):", bearer_token) +except SkyflowError as error: + # Handle any exceptions encountered during the token generation process + print(f"Error generating token from file path: {error}") +except Exception as e: + # Handle any other unexpected exceptions + print(f"Error generating token from file path: {e}") + +# Example 2: Generate Bearer Token using the credentials JSON string try: - skyflow_client.vault('').query(query_request) -except SkyflowError as e: - if e.data: - print(e.data) + # Provide the credentials JSON content as a string + skyflow_credentials = { + 'clientID': '', + 'clientName': '', + 'tokenURI': '', + 'keyID': '', + 'privateKey': '', + } + + # Convert credentials dictionary to JSON string + credentials_string = json.dumps(skyflow_credentials) + + # Check if the token is either not initialized or has expired + if not is_expired(bearer_token): + print("Generated Bearer Token (from string):", bearer_token) else: - print(e.message) + # Generate a new Bearer Token from the credentials string + token, _ = generate_bearer_token_from_creds(credentials_string) + bearer_token = token + print("Generated Bearer Token (from string):", bearer_token) +except SkyflowError as error: + # Handle any exceptions encountered during the token generation process + print(f"Error generating token from credentials string: {error}") +except Exception as e: + # Handle any other unexpected exceptions + print(f"Error generating token from credentials string: {e}") ``` -Sample Response +#### Generate bearer tokens with context +**Context-aware authorization** embeds context values into a bearer token during its generation and so you can reference those values in your policies. This enables more flexible access controls, such as helping you track end-user identity when making API calls using service accounts, and facilitates using signed data tokens during detokenization. + +A service account with the context_id identifier generates bearer tokens containing context information, represented as a JWT claim in a Skyflow-generated bearer token. Tokens generated from such service accounts include a context_identifier claim, are valid for 60 minutes, and can be used to make API calls to the Data and Management APIs, depending on the service account's permissions. +#### [Example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/service_account/token_generation_with_context_example.py): ```python -QueryResponse( - fields=[ - { - 'card_number': 'XXXXXXXXXXXX1112', - 'name': 'S***ar', - 'skyflow_id': '4f7af9f9-09e0-4f47-af8e-04c9b1ee1968', - 'tokenized_data': {} - } - ], - errors=[] +import json +from skyflow.error import SkyflowError +from skyflow.service_account import ( + generate_bearer_token, + generate_bearer_token_from_creds, + is_expired, ) -``` -## Logging +""" +Example program to generate a Bearer Token using Skyflow's BearerToken utility. +The token is generated using two approaches: +1. By providing the credentials.json file path. +2. By providing the contents of credentials.json as a string. +""" -The skyflow python SDK provides useful logging using python's inbuilt `logging` library. By default the logging level of the SDK is set to `LogLevel.ERROR`. This can be changed by using `set_log_level(log_level)` as shown below: +# Variable to store the generated token +bearer_token = '' -```python -from skyflow import Skyflow -from skyflow import LogLevel -from skyflow import Env +# Approach 1: Generate Bearer Token by specifying the path to the credentials.json file +try: + # Replace with the full path to your credentials.json file + file_path = 'YOUR_CREDENTIALS_FILE_PATH' -# To generate Bearer Token from credentials string. -skyflow_credentials = { + # Set context string (example: "abc") + options = {'ctx': 'abc'} + + # Check if the token is already generated and still valid + if not is_expired(bearer_token): + print("Generated Bearer Token (from file):", bearer_token) + else: + # Generate a new Bearer Token from the credentials file + token, _ = generate_bearer_token(file_path, options) # Set credentials from the file path and options + bearer_token = token + # Print the generated Bearer Token to the console + print("Generated Bearer Token (from file):", bearer_token) +except SkyflowError as error: + # Handle any exceptions encountered during the token generation process + print(f"Error generating token from file path: {error}") +except Exception as e: + # Handle any other unexpected exceptions + print(f"Error generating token from file path: {e}") + +# Approach 2: Generate Bearer Token by specifying the contents of credentials.json as a string +try: + # Provide the credentials JSON content as a string + skyflow_credentials = { 'clientID': '', 'clientName': '', 'tokenURI': '', 'keyID': '', 'privateKey': '', } -credentials_string = json.dumps(skyflow_credentials) -# Pass one of api_key, token, credentials_string & path as credentials -credentials = { - 'token': 'BEARER_TOKEN', # bearer token - # api_key: "API_KEY", # API_KEY - # path: "PATH", # path to credentials file - # credentials_string: credentials_string, # credentials as string -} + # Convert credentials dictionary to JSON string + credentials_string = json.dumps(skyflow_credentials) -client = ( - Skyflow.builder() - .add_vault_config({ - 'vault_id': 'VAULT_ID', # primary vault - 'cluster_id': 'CLUSTER_ID', # ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - 'env': Env.PROD, # Env by default it is set to PROD - 'credentials': credentials # individual credentials - }) - .add_skyflow_credentials(credentials) # skyflow credentials will be used if no individual credentials are passed - .set_log_level(LogLevel.INFO) # set log level by default it is set to ERROR - .build() + # Set context string (example: "abc") + options = {'ctx': 'abc'} + + # Check if the token is either not initialized or has expired + if not is_expired(bearer_token): + print("Generated Bearer Token (from string):", bearer_token) + else: + # Generate a new Bearer Token from the credentials string and options + token, _ = generate_bearer_token_from_creds(credentials_string, options) + bearer_token = token + print("Generated Bearer Token (from string):", bearer_token) +except SkyflowError as error: + # Handle any exceptions encountered during the token generation process + print(f"Error generating token from file path: {error}") +except Exception as e: + # Handle any other unexpected exceptions + print(f"Error generating token from credentials string: {e}") +``` + +#### Generate scoped bearer tokens +A service account with multiple roles can generate bearer tokens with access limited to a specific role by specifying the appropriate roleID. This can be used to limit access to specific roles for services with multiple responsibilities, such as segregating access for billing and analytics. The generated bearer tokens are valid for 60 minutes and can only execute operations permitted by the permissions associated with the designated role. + +#### [Example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/service_account/scoped_token_generation_example.py): +```python +import json +from skyflow.error import SkyflowError +from skyflow.service_account import ( + generate_bearer_token, + generate_bearer_token_from_creds, + is_expired, ) + +""" +Example program to generate a Scoped Token using Skyflow's BearerToken utility. +The token is generated by providing the file path to the credentials.json file +and specifying roles associated with the token. +""" + +# Variable to store the generated token +scoped_token = '' + +# Example: Generate Scoped Token by specifying the credentials.json file path +try: + # Specify the full file path to the service account's credentials.json file + file_path = 'YOUR_CREDENTIALS_FILE_PATH' + + # Set context string (example: "abc") + options = {'role_ids': ['ROLE_ID']} + + # Check if the token is already generated and still valid + if not is_expired(scoped_token): + print("Generated Bearer Token (from file):", scoped_token) + else: + # Generate a new Bearer Token from the credentials file and associated roles + scoped_token, _ = generate_bearer_token(file_path, options) # Set credentials from the file path and options + # Print the generated Bearer Token to the console + print("Generated Bearer Token (from file):", scoped_token) +except SkyflowError as error: + # Handle any exceptions encountered during the token generation process + print(f"Error generating token from file path: {error}") +except Exception as e: + # Handle any other unexpected exceptions + print(f"Error generating token from file path: {e}") ``` -Current the following 5 log levels are supported: +#### Generate signed data tokens +Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed with a service account's private key, adding an extra layer of protection. Signed tokens can only be detokenized by providing the signed data token along with a bearer token generated from the service account's credentials. The service account must have the necessary permissions and context to successfully detokenize the signed data tokens. -- `DEBUG`: +#### [Example](https://github.com/skyflowapi/skyflow-python/blob/v2/samples/service_account/signed_token_generation_example.py): +```python +import json +from skyflow.error import SkyflowError +from skyflow.service_account import ( + generate_signed_data_tokens, + generate_signed_data_tokens_from_creds, +) - When `LogLevel.DEBUG` is passed, all level of logs will be printed(DEBUG, INFO, WARN, ERROR) +# Example program to generate Signed Data Tokens using Skyflow's utilities. +# Signed Data Tokens can be generated in two ways: +# 1. By specifying the file path to the credentials.json file. +# 2. By providing the credentials as a JSON string. -- `INFO`: +# Example 1: Generate Signed Data Tokens using a credentials file +try: + # File path to the service account's credentials.json file + file_path = "CREDENTIALS_FILE_PATH" + + # Options for generating signed data tokens + options = { + "ctx": "CONTEX_ID", # Set the context value + "data_tokens": ["DATA_TOKEN1", "DATA_TOKEN2"], # Set the data tokens to be signed + "time_to_live": 30, # Set the data tokens to be signed + } + + # Generate and retrieve the signed data tokens + data_token, signed_data_token = generate_signed_data_tokens(file_path, options) + # Print the signed data tokens to the console + print("Signed Data Tokens (from file):", data_token, signed_data_token) +except SkyflowError as error: + # Handle any exceptions encountered during the token generation process + print(f"Error generating signed token from file path: {error}") +except Exception as e: + # Handle any other unexpected exceptions + print(f"Error generating signed token from file path: {e}") + +# Example 2: Generate Signed Data Tokens using credentials as a JSON string +try: + # JSON object containing Skyflow credentials + skyflow_credentials = { + "clientID": "", + "clientName": "", + "tokenURI": "", + "keyID": "", + "privateKey": "", + } - When `LogLevel.INFO` is passed, INFO logs for every event that has occurred during the SDK flow execution will be printed along with WARN and ERROR logs + # Convert credentials dictionary to JSON string + credentials_string = json.dumps(skyflow_credentials) -- `WARN`: + options = { + "ctx": "CONTEX_ID", # Context value associated with the token + "data_tokens": ["DATA_TOKEN1", "DATA_TOKEN2"], # Set the data tokens to be signed + "time_to_live": 30, # Set the token's time-to-live (TTL) in seconds + } - When `LogLevel.WARN` is passed, WARN and ERROR logs will be printed + # Generate and retrieve the signed data tokens + data_token, signed_data_token = generate_signed_data_tokens_from_creds(credentials_string, options) + # Print the signed data tokens to the console + print("Signed Data Tokens (from string):", data_token, signed_data_token) +except SkyflowError as error: + # Handle any exceptions encountered during the token generation process + print(f"Error generating signed token from credentials string: {error}") +except Exception as e: + # Handle any other unexpected exceptions + print(f"Error generating signed token from credentials string: {e}") -- `ERROR`: +``` - When `LogLevel.ERROR` is passed, only ERROR logs will be printed. +Notes: +- The `time_to_live` (TTL) value should be specified in seconds. +- By default, the TTL value is set to 60 seconds. +## Logging + +The SDK provides logging using python's inbuilt `logging` library. By default the logging level of the SDK is set to `LogLevel.ERROR`. This can be changed by using `set_log_level(log_level)` as shown below: + +Currently, the following five log levels are supported: +- `DEBUG`: +When `LogLevel.DEBUG` is passed, logs at all levels will be printed (DEBUG, INFO, WARN, ERROR). +- `INFO`: +When `LogLevel.INFO` is passed, INFO logs for every event that occurs during SDK flow execution will be printed, along with WARN and ERROR logs. +- `WARN`: +When `LogLevel.WARN` is passed, only WARN and ERROR logs will be printed. +- `ERROR`: +When `LogLevel.ERROR` is passed, only ERROR logs will be printed. - `OFF`: +`LogLevel.OFF` can be used to turn off all logging from the Skyflow Python SDK. + +**Note:** The ranking of logging levels is as follows: `DEBUG` < `INFO` < `WARN` < `ERROR` < `OFF`. + +```python +import json +from skyflow import Skyflow +from skyflow import LogLevel +from skyflow import Env + +""" +This example demonstrates how to configure the Skyflow client with custom log levels and authentication credentials (either token, credentials string, or other methods). It also shows how to configure a vault connection using specific parameters. +1. Set up credentials with a Bearer token or credentials string. +2. Define the Vault configuration. +3. Build the Skyflow client with the chosen configuration and set log level. +4. Example of changing the log level from ERROR (default) to INFO. +""" + +# Step 1: Set up credentials - either pass token or use credentials string +# In this case, we are using a Bearer token for authentication +credentials = { + 'token': '', # Replace with actual Bearer token +} + +# Step 2: Define the Vault configuration +# Configure the vault with necessary details like vault ID, cluster ID, and environment +vault_config = { + 'vault_id': '', # Replace with actual Vault ID (primary vault) + 'cluster_id': '', # Replace with actual Cluster ID (from vault URL) + 'env': Env.PROD, # Set the environment (default is PROD) + 'credentials': credentials # Set credentials for the vault (either token or credentials) +} + +# Step 3: Define additional Skyflow credentials (optional, if needed for credentials string) +skyflow_credentials = { + 'clientID': '', # Replace with your client ID + 'clientName': '', # Replace with your client name + 'tokenURI': '', # Replace with your token URI + 'keyID': '', # Replace with your key ID + 'privateKey': '', # Replace with your private key +} - `LogLevel.OFF` can be used to turn off all logging from the Skyflow SDK. +# Convert the credentials object to a json string format to be used for generating a Bearer Token +credentials_string = json.dumps(skyflow_credentials) # Set credentials string -`Note`: The ranking of logging levels is as follows : `DEBUG` < `INFO` < `WARN` < `ERROR` < `OFF` +# Step 4: Build the Skyflow client with the chosen configuration and log level +skyflow_client = ( + Skyflow.builder() + .add_vault_config(vault_config) # Add the Vault configuration + .add_skyflow_credentials(skyflow_credentials) # Use Skyflow credentials if no token is passed + .set_log_level(LogLevel.INFO) # Set log level to INFO (default is ERROR) + .build() # Build the Skyflow client +) + +# Now, the Skyflow client is ready to use with the specified log level and credentials +print('Skyflow client has been successfully configured with log level: INFO.') +``` ## Reporting a Vulnerability -If you discover a potential security issue in this project, please reach out to us at security@skyflow.com. Please do not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. +If you discover a potential security issue in this project, please reach out to us at **security@skyflow.com**. Please do not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. From b096bcf52bec20f20b610395aef0b755a4cdf1bc Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 4 Mar 2025 18:21:07 +0530 Subject: [PATCH 04/24] SK-1906 Improve debugging in connections --- skyflow/utils/_utils.py | 5 +++++ skyflow/vault/controller/_connections.py | 3 ++- tests/vault/controller/test__connection.py | 20 ++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/skyflow/utils/_utils.py b/skyflow/utils/_utils.py index 5002956a..d3c21071 100644 --- a/skyflow/utils/_utils.py +++ b/skyflow/utils/_utils.py @@ -341,6 +341,11 @@ def parse_invoke_connection_response(api_response: requests.Response): if 'x-request-id' in api_response.headers: message += ' - request id: ' + api_response.headers['x-request-id'] + + if 'error-from-client' in api_response.headers: + error_from_client = api_response.headers['error-from-client'] + details = [{ "error_from_client": error_from_client }] + raise SkyflowError(message, status_code, details=details) raise SkyflowError(message, status_code) diff --git a/skyflow/vault/controller/_connections.py b/skyflow/vault/controller/_connections.py index 2fc52f11..9f067d92 100644 --- a/skyflow/vault/controller/_connections.py +++ b/skyflow/vault/controller/_connections.py @@ -27,7 +27,7 @@ def invoke(self, request: InvokeConnectionRequest): invoke_connection_request.headers['sky-metadata'] = json.dumps(get_metrics()) - log_info(SkyflowMessages.Info.INVOKE_CONNECTION_TRIGGERED, self.__vault_client.get_logger()) + log_info(SkyflowMessages.Info.INVOKE_CONNECTION_TRIGGERED.value, self.__vault_client.get_logger()) try: response = session.send(invoke_connection_request) @@ -36,5 +36,6 @@ def invoke(self, request: InvokeConnectionRequest): return invoke_connection_response except Exception as e: + if isinstance(e, SkyflowError): raise e raise SkyflowError(SkyflowMessages.Error.INVOKE_CONNECTION_FAILED.value, SkyflowMessages.ErrorCodes.SERVER_ERROR.value) \ No newline at end of file diff --git a/tests/vault/controller/test__connection.py b/tests/vault/controller/test__connection.py index 0bd3d293..5b5a106d 100644 --- a/tests/vault/controller/test__connection.py +++ b/tests/vault/controller/test__connection.py @@ -100,5 +100,25 @@ def test_invoke_request_error(self, mock_send): with self.assertRaises(SkyflowError) as context: self.connection.invoke(request) self.assertEqual(context.exception.message, SkyflowMessages.Error.INVOKE_CONNECTION_FAILED.value) + self.assertTrue(context.exception.details['error_from_client']) + @patch('requests.Session.send') + def test_invoke_request_error_from_client(self, mock_send): + mock_response = Mock() + mock_response.status_code = FAILURE_STATUS_CODE + mock_response.content = ERROR_RESPONSE_CONTENT + mock_response.headers = {'error-from-client': True} + mock_send.return_value = mock_response + + request = InvokeConnectionRequest( + method=RequestMethod.POST, + body=VALID_BODY, + path_params=VALID_PATH_PARAMS, + headers=VALID_HEADERS, + query_params=VALID_QUERY_PARAMS + ) + with self.assertRaises(SkyflowError) as context: + self.connection.invoke(request) + self.assertEqual(context.exception.message, SkyflowMessages.Error.INVOKE_CONNECTION_FAILED.value) + self.assertTrue(context.exception.details['error_from_client']) From 74628e555634735b4f8c3645c309036a8c287b2b Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Tue, 4 Mar 2025 22:25:09 +0530 Subject: [PATCH 05/24] SK-1906: Fix invoke connection test case --- tests/vault/controller/test__connection.py | 36 ++++++++++------------ 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/tests/vault/controller/test__connection.py b/tests/vault/controller/test__connection.py index 5b5a106d..9723b91a 100644 --- a/tests/vault/controller/test__connection.py +++ b/tests/vault/controller/test__connection.py @@ -1,8 +1,8 @@ import unittest from unittest.mock import Mock, patch - +import requests from skyflow.error import SkyflowError -from skyflow.utils import SkyflowMessages +from skyflow.utils import SkyflowMessages, parse_invoke_connection_response from skyflow.utils.enums import RequestMethod from skyflow.vault.connection import InvokeConnectionRequest from skyflow.vault.controller import Connection @@ -21,7 +21,7 @@ INVALID_HEADERS = "invalid_headers" INVALID_BODY = "invalid_body" FAILURE_STATUS_CODE = 400 -ERROR_RESPONSE_CONTENT = '{"error": {"message": "error occurred"}}' +ERROR_RESPONSE_CONTENT = b'{"error": {"message": "Invalid Request"}}' class TestConnection(unittest.TestCase): def setUp(self): @@ -100,25 +100,21 @@ def test_invoke_request_error(self, mock_send): with self.assertRaises(SkyflowError) as context: self.connection.invoke(request) self.assertEqual(context.exception.message, SkyflowMessages.Error.INVOKE_CONNECTION_FAILED.value) - self.assertTrue(context.exception.details['error_from_client']) - @patch('requests.Session.send') - def test_invoke_request_error_from_client(self, mock_send): - mock_response = Mock() + def test_parse_invoke_connection_response_error_from_client(self): + mock_response = Mock(spec=requests.Response) mock_response.status_code = FAILURE_STATUS_CODE mock_response.content = ERROR_RESPONSE_CONTENT - mock_response.headers = {'error-from-client': True} - mock_send.return_value = mock_response - - request = InvokeConnectionRequest( - method=RequestMethod.POST, - body=VALID_BODY, - path_params=VALID_PATH_PARAMS, - headers=VALID_HEADERS, - query_params=VALID_QUERY_PARAMS - ) + mock_response.headers = { + 'error-from-client': 'true', + 'x-request-id': '12345' + } + mock_response.raise_for_status.side_effect = requests.HTTPError() with self.assertRaises(SkyflowError) as context: - self.connection.invoke(request) - self.assertEqual(context.exception.message, SkyflowMessages.Error.INVOKE_CONNECTION_FAILED.value) - self.assertTrue(context.exception.details['error_from_client']) + parse_invoke_connection_response(mock_response) + + exception = context.exception + + self.assertTrue(any(detail.get('error_from_client') == 'true' for detail in exception.details)) + From 9cd613b979ac0788910521a690fa427a8ae241c6 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 6 Mar 2025 21:05:55 +0530 Subject: [PATCH 06/24] SK-1934 Fix inconsistent error handling for invoke connections --- skyflow/utils/_skyflow_messages.py | 1 + skyflow/utils/_utils.py | 39 +++++++++++----------- skyflow/vault/controller/_connections.py | 3 +- tests/utils/test__utils.py | 5 +-- tests/vault/controller/test__connection.py | 11 ++++-- 5 files changed, 34 insertions(+), 25 deletions(-) diff --git a/skyflow/utils/_skyflow_messages.py b/skyflow/utils/_skyflow_messages.py index 954c5e14..26ca4a25 100644 --- a/skyflow/utils/_skyflow_messages.py +++ b/skyflow/utils/_skyflow_messages.py @@ -275,6 +275,7 @@ class ErrorLogs(Enum): UPDATE_REQUEST_REJECTED = f"{ERROR}: [{error_prefix}] Update request resulted in failure." QUERY_REQUEST_REJECTED = f"{ERROR}: [{error_prefix}] Query request resulted in failure." GET_REQUEST_REJECTED = f"{ERROR}: [{error_prefix}] Get request resulted in failure." + INVOKE_CONNECTION_REQUEST_REJECTED = f"{ERROR}: [{error_prefix}] Invoke connection request resulted in failure." class Interface(Enum): INSERT = "INSERT" diff --git a/skyflow/utils/_utils.py b/skyflow/utils/_utils.py index d3c21071..2261d3e6 100644 --- a/skyflow/utils/_utils.py +++ b/skyflow/utils/_utils.py @@ -327,29 +327,30 @@ def parse_invoke_connection_response(api_response: requests.Response): invoke_connection_response.response = json_content return invoke_connection_response - except: + except Exception as e: raise SkyflowError(SkyflowMessages.Error.RESPONSE_NOT_JSON.value.format(content), status_code) except HTTPError: - message = SkyflowMessages.Error.API_ERROR.value.format(status_code) - if api_response and api_response.content: - try: - error_response = json.loads(content) - if isinstance(error_response.get('error'), dict) and 'message' in error_response['error']: - message = error_response['error']['message'] - except json.JSONDecodeError: - message = SkyflowMessages.Error.RESPONSE_NOT_JSON.value.format(content) - - if 'x-request-id' in api_response.headers: - message += ' - request id: ' + api_response.headers['x-request-id'] - - if 'error-from-client' in api_response.headers: - error_from_client = api_response.headers['error-from-client'] - details = [{ "error_from_client": error_from_client }] - raise SkyflowError(message, status_code, details=details) - + message = SkyflowMessages.Error.API_ERROR.value.format(status_code) + try: + error_response = json.loads(content) + request_id = api_response.headers['x-request-id'] + error_from_client = api_response.headers.get('error-from-client') + + status_code = error_response.get('error', {}).get('http_code', 500) # Default to 500 if not found + http_status = error_response.get('error', {}).get('http_status') + grpc_code = error_response.get('error', {}).get('grpc_code') + details = error_response.get('error', {}).get('details') + message = error_response.get('error', {}).get('message', "An unknown error occurred.") + + if error_from_client is not None: + if details is None: details = [] + details.append({'error_from_client': error_from_client}) + + raise SkyflowError(message, status_code, request_id, grpc_code, http_status, details) + except json.JSONDecodeError: + message = SkyflowMessages.Error.RESPONSE_NOT_JSON.value.format(content) raise SkyflowError(message, status_code) - def log_and_reject_error(description, status_code, request_id, http_status=None, grpc_code=None, details=None, logger = None): raise SkyflowError(description, status_code, request_id, grpc_code, http_status, details) diff --git a/skyflow/vault/controller/_connections.py b/skyflow/vault/controller/_connections.py index 9f067d92..81c6ea10 100644 --- a/skyflow/vault/controller/_connections.py +++ b/skyflow/vault/controller/_connections.py @@ -3,7 +3,7 @@ from skyflow.error import SkyflowError from skyflow.utils import construct_invoke_connection_request, SkyflowMessages, get_metrics, \ parse_invoke_connection_response -from skyflow.utils.logger import log_info +from skyflow.utils.logger import log_info, log_error_log from skyflow.vault.connection import InvokeConnectionRequest @@ -36,6 +36,7 @@ def invoke(self, request: InvokeConnectionRequest): return invoke_connection_response except Exception as e: + log_error_log(SkyflowMessages.ErrorLogs.INVOKE_CONNECTION_REQUEST_REJECTED.value, self.__vault_client.get_logger()) if isinstance(e, SkyflowError): raise e raise SkyflowError(SkyflowMessages.Error.INVOKE_CONNECTION_FAILED.value, SkyflowMessages.ErrorCodes.SERVER_ERROR.value) \ No newline at end of file diff --git a/tests/utils/test__utils.py b/tests/utils/test__utils.py index c9010c98..e70afc0e 100644 --- a/tests/utils/test__utils.py +++ b/tests/utils/test__utils.py @@ -344,7 +344,8 @@ def test_parse_invoke_connection_response_http_error_with_json_error_message(sel with self.assertRaises(SkyflowError) as context: parse_invoke_connection_response(mock_response) - self.assertEqual(context.exception.message, "Not Found - request id: 1234") + self.assertEqual(context.exception.message, "Not Found") + self.assertEqual(context.exception.request_id, "1234") @patch("requests.Response") def test_parse_invoke_connection_response_http_error_without_json_error_message(self, mock_response): @@ -357,7 +358,7 @@ def test_parse_invoke_connection_response_http_error_without_json_error_message( with self.assertRaises(SkyflowError) as context: parse_invoke_connection_response(mock_response) - self.assertEqual(context.exception.message, SkyflowMessages.Error.RESPONSE_NOT_JSON.value.format("Internal Server Error") + " - request id: 1234") + self.assertEqual(context.exception.message, SkyflowMessages.Error.RESPONSE_NOT_JSON.value.format("Internal Server Error")) @patch("skyflow.utils._utils.log_and_reject_error") def test_handle_exception_json_error(self, mock_log_and_reject_error): diff --git a/tests/vault/controller/test__connection.py b/tests/vault/controller/test__connection.py index 9723b91a..61be3163 100644 --- a/tests/vault/controller/test__connection.py +++ b/tests/vault/controller/test__connection.py @@ -4,6 +4,7 @@ from skyflow.error import SkyflowError from skyflow.utils import SkyflowMessages, parse_invoke_connection_response from skyflow.utils.enums import RequestMethod +from skyflow.utils._version import SDK_VERSION from skyflow.vault.connection import InvokeConnectionRequest from skyflow.vault.controller import Connection @@ -21,7 +22,8 @@ INVALID_HEADERS = "invalid_headers" INVALID_BODY = "invalid_body" FAILURE_STATUS_CODE = 400 -ERROR_RESPONSE_CONTENT = b'{"error": {"message": "Invalid Request"}}' +ERROR_RESPONSE_CONTENT = '"message": "Invalid Request"' +ERROR_FROM_CLIENT_RESPONSE_CONTENT = b'{"error": {"message": "Invalid Request"}}' class TestConnection(unittest.TestCase): def setUp(self): @@ -99,12 +101,14 @@ def test_invoke_request_error(self, mock_send): with self.assertRaises(SkyflowError) as context: self.connection.invoke(request) - self.assertEqual(context.exception.message, SkyflowMessages.Error.INVOKE_CONNECTION_FAILED.value) + self.assertEqual(context.exception.message, f'Skyflow Python SDK {SDK_VERSION} Response {ERROR_RESPONSE_CONTENT} is not valid JSON.') + self.assertEqual(context.exception.message, SkyflowMessages.Error.RESPONSE_NOT_JSON.value.format(ERROR_RESPONSE_CONTENT)) + self.assertEqual(context.exception.http_code, 400) def test_parse_invoke_connection_response_error_from_client(self): mock_response = Mock(spec=requests.Response) mock_response.status_code = FAILURE_STATUS_CODE - mock_response.content = ERROR_RESPONSE_CONTENT + mock_response.content = ERROR_FROM_CLIENT_RESPONSE_CONTENT mock_response.headers = { 'error-from-client': 'true', 'x-request-id': '12345' @@ -117,4 +121,5 @@ def test_parse_invoke_connection_response_error_from_client(self): exception = context.exception self.assertTrue(any(detail.get('error_from_client') == 'true' for detail in exception.details)) + self.assertEqual(exception.request_id, '12345') From 6ee188371cd806f59b3da9403a8027afde048bb9 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Mon, 10 Mar 2025 16:04:25 +0530 Subject: [PATCH 07/24] SK-1874: Support for the combination of tokens and redaction type in detokenize API (#164) * SK-1874: Support for the combination of tokens and redaction type in the Detokenize API. (#156) --- samples/vault_api/detokenize_records.py | 15 +++++++++++---- setup.py | 2 +- skyflow/utils/_skyflow_messages.py | 6 ++++-- skyflow/utils/_version.py | 2 +- skyflow/utils/validations/_validations.py | 21 +++++++++++++++------ skyflow/vault/controller/_vault.py | 4 ++-- skyflow/vault/tokens/_detokenize_request.py | 5 ++--- tests/vault/controller/test__vault.py | 12 ++++++++++-- 8 files changed, 46 insertions(+), 21 deletions(-) diff --git a/samples/vault_api/detokenize_records.py b/samples/vault_api/detokenize_records.py index b76aa89e..e93d5a18 100644 --- a/samples/vault_api/detokenize_records.py +++ b/samples/vault_api/detokenize_records.py @@ -52,13 +52,20 @@ def perform_detokenization(): ) # Step 4: Prepare Detokenization Data - detokenize_data = ['token1', 'token2', 'token3'] # Tokens to be detokenized - redaction_type = RedactionType.REDACTED + detokenize_data = [ + { + 'token': '', # Token to be detokenized + 'redaction': RedactionType.REDACTED + }, + { + 'token': '', # Token to be detokenized + 'redaction': RedactionType.MASKED + } + ] # Create Detokenize Request detokenize_request = DetokenizeRequest( - tokens=detokenize_data, - redaction_type=redaction_type, + data=detokenize_data, continue_on_error=True # Continue processing on errors ) diff --git a/setup.py b/setup.py index 55c45d4f..c7b17c3d 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ if sys.version_info < (3, 8): raise RuntimeError("skyflow requires Python 3.8+") -current_version = '2.0.0b1' +current_version = '2.0.0b1.dev0+dcb5ddc' setup( name='skyflow', diff --git a/skyflow/utils/_skyflow_messages.py b/skyflow/utils/_skyflow_messages.py index 954c5e14..71fc76f9 100644 --- a/skyflow/utils/_skyflow_messages.py +++ b/skyflow/utils/_skyflow_messages.py @@ -101,7 +101,7 @@ class Error(Enum): INVOKE_CONNECTION_FAILED = f"{error_prefix} Invoke Connection operation failed." INVALID_IDS_TYPE = f"{error_prefix} Validation error. 'ids' has a value of type {{}}. Specify 'ids' as list." - INVALID_REDACTION_TYPE = f"{error_prefix} Validation error. 'redaction' has a value of type {{}}. Specify 'redaction' as type Skyflow.Redaction." + INVALID_REDACTION_TYPE = f"{error_prefix} Validation error. 'redaction' has a value of type {{}}. Specify 'redaction' as type Skyflow.RedactionType." INVALID_COLUMN_NAME = f"{error_prefix} Validation error. 'column' has a value of type {{}}. Specify 'column' as a string." INVALID_COLUMN_VALUE = f"{error_prefix} Validation error. columnValues key has a value of type {{}}. Specify columnValues key as list." INVALID_FIELDS_VALUE = f"{error_prefix} Validation error. fields key has a value of type{{}}. Specify fields key as list." @@ -117,8 +117,10 @@ class Error(Enum): UPDATE_FIELD_KEY_ERROR = f"{error_prefix} Validation error. Fields are empty in an update payload. Specify at least one field." INVALID_FIELDS_TYPE = f"{error_prefix} Validation error. The 'data' key has a value of type {{}}. Specify 'data' as a dictionary." IDS_KEY_ERROR = f"{error_prefix} Validation error. 'ids' key is missing from the payload. Specify an 'ids' key." - INVALID_TOKENS_LIST_VALUE = f"{error_prefix} Validation error. The 'tokens' key has a value of type {{}}. Specify 'tokens' as a list." + INVALID_TOKENS_LIST_VALUE = f"{error_prefix} Validation error. The 'data' field is invalid. Specify 'data' as a list of dictionaries containing 'token' and 'redaction'." + INVALID_DATA_FOR_DETOKENIZE = f"{error_prefix}" EMPTY_TOKENS_LIST_VALUE = f"{error_prefix} Validation error. Tokens are empty in detokenize payload. Specify at lease one token" + INVALID_TOKEN_TYPE = f"{ERROR}: [{error_prefix}] Invalid {{}} request. Tokens should be of type string." INVALID_TOKENIZE_PARAMETERS = f"{error_prefix} Validation error. The 'values' key has a value of type {{}}. Specify 'tokenize_parameters' as a list." EMPTY_TOKENIZE_PARAMETERS = f"{error_prefix} Validation error. Tokenize values are empty in tokenize payload. Specify at least one parameter." diff --git a/skyflow/utils/_version.py b/skyflow/utils/_version.py index 64d4c6b5..a17f3809 100644 --- a/skyflow/utils/_version.py +++ b/skyflow/utils/_version.py @@ -1 +1 @@ -SDK_VERSION = '2.0.0b1' \ No newline at end of file +SDK_VERSION = '2.0.0b1.dev0+dcb5ddc' \ No newline at end of file diff --git a/skyflow/utils/validations/_validations.py b/skyflow/utils/validations/_validations.py index c3026e75..5b7827a9 100644 --- a/skyflow/utils/validations/_validations.py +++ b/skyflow/utils/validations/_validations.py @@ -502,19 +502,28 @@ def validate_update_request(logger, request): invalid_input_error_code) def validate_detokenize_request(logger, request): - if not isinstance(request.redaction_type, RedactionType): - raise SkyflowError(SkyflowMessages.Error.INVALID_REDACTION_TYPE.value.format(type(request.redaction_type)), invalid_input_error_code) - if not isinstance(request.continue_on_error, bool): raise SkyflowError(SkyflowMessages.Error.INVALID_CONTINUE_ON_ERROR_TYPE.value, invalid_input_error_code) - if not len(request.tokens): + if not isinstance(request.data, list): + raise SkyflowError(SkyflowMessages.Error.INVALID_TOKENS_LIST_VALUE.value(type(request.data)), invalid_input_error_code) + + if not len(request.data): log_error_log(SkyflowMessages.ErrorLogs.TOKENS_REQUIRED.value.format("DETOKENIZE"), logger = logger) log_error_log(SkyflowMessages.ErrorLogs.EMPTY_TOKENS.value.format("DETOKENIZE"), logger = logger) raise SkyflowError(SkyflowMessages.Error.EMPTY_TOKENS_LIST_VALUE.value, invalid_input_error_code) - if not isinstance(request.tokens, list): - raise SkyflowError(SkyflowMessages.Error.INVALID_TOKENS_LIST_VALUE.value(type(request.tokens)), invalid_input_error_code) + for item in request.data: + if 'token' not in item or 'redaction' not in item: + raise SkyflowError(SkyflowMessages.Error.INVALID_TOKENS_LIST_VALUE.value(type(request.data)), invalid_input_error_code) + token = item.get('token') + redaction = item.get('redaction') + + if not isinstance(token, str) or not token: + raise SkyflowError(SkyflowMessages.Error.INVALID_TOKEN_TYPE.value.format("DETOKENIZE"), invalid_input_error_code) + + if not isinstance(redaction, RedactionType) or not redaction: + raise SkyflowError(SkyflowMessages.Error.INVALID_REDACTION_TYPE.value.format(type(redaction)), invalid_input_error_code) def validate_tokenize_request(logger, request): parameters = request.values diff --git a/skyflow/vault/controller/_vault.py b/skyflow/vault/controller/_vault.py index ee6a4ae5..9867443f 100644 --- a/skyflow/vault/controller/_vault.py +++ b/skyflow/vault/controller/_vault.py @@ -230,8 +230,8 @@ def detokenize(self, request: DetokenizeRequest): log_info(SkyflowMessages.Info.DETOKENIZE_REQUEST_RESOLVED.value, self.__vault_client.get_logger()) self.__initialize() tokens_list = [ - V1DetokenizeRecordRequest(token=token, redaction=request.redaction_type.value) - for token in request.tokens + V1DetokenizeRecordRequest(token=item.get('token'), redaction=item.get('redaction').value) + for item in request.data ] payload = V1DetokenizePayload(detokenization_parameters=tokens_list, continue_on_error=request.continue_on_error) tokens_api = self.__vault_client.get_tokens_api() diff --git a/skyflow/vault/tokens/_detokenize_request.py b/skyflow/vault/tokens/_detokenize_request.py index 5e3bc041..73a5368e 100644 --- a/skyflow/vault/tokens/_detokenize_request.py +++ b/skyflow/vault/tokens/_detokenize_request.py @@ -1,7 +1,6 @@ from skyflow.utils.enums.redaction_type import RedactionType class DetokenizeRequest: - def __init__(self, tokens, redaction_type = RedactionType.PLAIN_TEXT, continue_on_error = False): - self.tokens = tokens - self.redaction_type = redaction_type + def __init__(self, data, continue_on_error = False): + self.data = data self.continue_on_error = continue_on_error \ No newline at end of file diff --git a/tests/vault/controller/test__vault.py b/tests/vault/controller/test__vault.py index 0d2ea3d8..6e0805e0 100644 --- a/tests/vault/controller/test__vault.py +++ b/tests/vault/controller/test__vault.py @@ -455,8 +455,16 @@ def test_query_successful(self, mock_parse_response, mock_validate): @patch("skyflow.vault.controller._vault.parse_detokenize_response") def test_detokenize_successful(self, mock_parse_response, mock_validate): request = DetokenizeRequest( - tokens=["token1", "token2"], - redaction_type=RedactionType.PLAIN_TEXT, + data=[ + { + 'token': 'token1', + 'redaction': RedactionType.PLAIN_TEXT + }, + { + 'token': 'token2', + 'redaction': RedactionType.PLAIN_TEXT + } + ], continue_on_error=False ) From 5a63cc9d9fa311fb683e06217eb96385a6cd5211 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 10 Mar 2025 11:53:52 +0000 Subject: [PATCH 08/24] [AUTOMATED] Private Release 2.0.0b1.dev0+3d4ee51 --- setup.py | 2 +- skyflow/utils/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index c7b17c3d..9d68a420 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ if sys.version_info < (3, 8): raise RuntimeError("skyflow requires Python 3.8+") -current_version = '2.0.0b1.dev0+dcb5ddc' +current_version = '2.0.0b1.dev0+3d4ee51' setup( name='skyflow', diff --git a/skyflow/utils/_version.py b/skyflow/utils/_version.py index a17f3809..522115a4 100644 --- a/skyflow/utils/_version.py +++ b/skyflow/utils/_version.py @@ -1 +1 @@ -SDK_VERSION = '2.0.0b1.dev0+dcb5ddc' \ No newline at end of file +SDK_VERSION = '2.0.0b1.dev0+3d4ee51' \ No newline at end of file From f760bc0979da6e5e8736a01731a3ccd262b2e9fa Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Mon, 17 Mar 2025 18:51:00 +0530 Subject: [PATCH 09/24] SK-1908: Migrate Python SDK from openapi generator to Fern SDK generator (#168) * SK-1908: Migrate from openapi generator to Fern --- ci-scripts/bump_version.sh | 2 + requirements.txt | 3 +- setup.py | 27 +- skyflow/client/skyflow.py | 2 +- skyflow/generated/rest/__init__.py | 217 +- skyflow/generated/rest/api/__init__.py | 9 - skyflow/generated/rest/api/audit_api.py | 848 ----- .../generated/rest/api/authentication_api.py | 319 -- skyflow/generated/rest/api/bin_lookup_api.py | 315 -- skyflow/generated/rest/api/query_api.py | 330 -- skyflow/generated/rest/api/records_api.py | 3310 ----------------- skyflow/generated/rest/api/tokens_api.py | 623 ---- skyflow/generated/rest/api_client.py | 789 ---- skyflow/generated/rest/api_response.py | 21 - skyflow/generated/rest/audit/__init__.py | 19 + skyflow/generated/rest/audit/client.py | 509 +++ .../generated/rest/audit/types/__init__.py | 27 + ...t_events_request_filter_ops_action_type.py | 27 + ..._request_filter_ops_context_access_type.py | 7 + ...s_request_filter_ops_context_actor_type.py | 7 + ...ts_request_filter_ops_context_auth_mode.py | 7 + ...events_request_filter_ops_resource_type.py | 39 + ..._audit_events_request_sort_ops_order_by.py | 5 + .../generated/rest/authentication/__init__.py | 2 + .../generated/rest/authentication/client.py | 264 ++ skyflow/generated/rest/bin_lookup/__init__.py | 2 + skyflow/generated/rest/bin_lookup/client.py | 204 + skyflow/generated/rest/client.py | 160 + skyflow/generated/rest/configuration.py | 464 --- skyflow/generated/rest/core/__init__.py | 47 + skyflow/generated/rest/core/api_error.py | 15 + skyflow/generated/rest/core/client_wrapper.py | 76 + skyflow/generated/rest/core/datetime_utils.py | 28 + skyflow/generated/rest/core/file.py | 67 + skyflow/generated/rest/core/http_client.py | 499 +++ .../generated/rest/core/jsonable_encoder.py | 101 + .../generated/rest/core/pydantic_utilities.py | 296 ++ skyflow/generated/rest/core/query_encoder.py | 58 + .../rest/core/remove_none_from_dict.py | 11 + .../generated/rest/core/request_options.py | 35 + skyflow/generated/rest/core/serialization.py | 272 ++ skyflow/generated/rest/environment.py | 8 + skyflow/generated/rest/errors/__init__.py | 7 + .../rest/errors/bad_request_error.py | 9 + .../generated/rest/errors/not_found_error.py | 9 + .../rest/errors/unauthorized_error.py | 9 + skyflow/generated/rest/exceptions.py | 200 - skyflow/generated/rest/models/__init__.py | 70 - .../models/audit_event_audit_resource_type.py | 66 - .../rest/models/audit_event_context.py | 113 - .../generated/rest/models/audit_event_data.py | 88 - .../rest/models/audit_event_http_info.py | 90 - .../rest/models/batch_record_method.py | 41 - .../rest/models/context_access_type.py | 39 - .../rest/models/context_auth_mode.py | 40 - .../detokenize_record_response_value_type.py | 45 - .../generated/rest/models/googlerpc_status.py | 100 - skyflow/generated/rest/models/protobuf_any.py | 101 - .../query_service_execute_query_body.py | 88 - .../record_service_batch_operation_body.py | 101 - .../record_service_bulk_delete_record_body.py | 88 - .../record_service_insert_record_body.py | 105 - .../record_service_update_record_body.py | 97 - .../rest/models/redaction_enum_redaction.py | 40 - .../rest/models/request_action_type.py | 54 - .../rest/models/v1_audit_after_options.py | 90 - .../rest/models/v1_audit_event_response.py | 98 - .../rest/models/v1_audit_response.py | 102 - .../rest/models/v1_audit_response_event.py | 110 - .../models/v1_audit_response_event_request.py | 114 - .../models/v1_batch_operation_response.py | 90 - .../generated/rest/models/v1_batch_record.py | 108 - .../rest/models/v1_bin_list_request.py | 98 - .../rest/models/v1_bin_list_response.py | 96 - .../models/v1_bulk_delete_record_response.py | 88 - .../models/v1_bulk_get_record_response.py | 96 - skyflow/generated/rest/models/v1_byot.py | 39 - skyflow/generated/rest/models/v1_card.py | 104 - .../rest/models/v1_delete_file_response.py | 90 - .../rest/models/v1_delete_record_response.py | 90 - .../rest/models/v1_detokenize_payload.py | 100 - .../models/v1_detokenize_record_request.py | 91 - .../models/v1_detokenize_record_response.py | 95 - .../rest/models/v1_detokenize_response.py | 96 - .../generated/rest/models/v1_field_records.py | 90 - .../rest/models/v1_file_av_scan_status.py | 45 - .../rest/models/v1_get_auth_token_request.py | 98 - .../rest/models/v1_get_auth_token_response.py | 90 - .../v1_get_file_scan_status_response.py | 89 - .../rest/models/v1_get_query_response.py | 96 - .../rest/models/v1_insert_record_response.py | 96 - .../generated/rest/models/v1_member_type.py | 39 - .../rest/models/v1_record_meta_properties.py | 90 - .../rest/models/v1_tokenize_payload.py | 96 - .../rest/models/v1_tokenize_record_request.py | 90 - .../models/v1_tokenize_record_response.py | 88 - .../rest/models/v1_tokenize_response.py | 96 - .../rest/models/v1_update_record_response.py | 90 - .../rest/models/v1_vault_field_mapping.py | 92 - .../rest/models/v1_vault_schema_config.py | 96 - skyflow/generated/rest/query/__init__.py | 2 + skyflow/generated/rest/query/client.py | 181 + skyflow/generated/rest/records/__init__.py | 13 + skyflow/generated/rest/records/client.py | 1978 ++++++++++ .../generated/rest/records/types/__init__.py | 11 + ...ervice_bulk_get_record_request_order_by.py | 5 + ...rvice_bulk_get_record_request_redaction.py | 7 + ...rd_service_get_record_request_redaction.py | 7 + skyflow/generated/rest/rest.py | 258 -- skyflow/generated/rest/tokens/__init__.py | 2 + skyflow/generated/rest/tokens/client.py | 395 ++ skyflow/generated/rest/types/__init__.py | 91 + .../types/audit_event_audit_resource_type.py | 39 + .../rest/types/audit_event_context.py | 90 + .../generated/rest/types/audit_event_data.py | 26 + .../rest/types/audit_event_http_info.py | 29 + .../rest/types/batch_record_method.py | 5 + .../rest/types/context_access_type.py | 5 + .../generated/rest/types/context_auth_mode.py | 5 + .../detokenize_record_response_value_type.py | 7 + .../generated/rest/types/googlerpc_status.py | 22 + skyflow/generated/rest/types/protobuf_any.py | 21 + .../rest/types/redaction_enum_redaction.py | 5 + .../rest/types/request_action_type.py | 27 + .../rest/types/v_1_audit_after_options.py | 31 + .../rest/types/v_1_audit_event_response.py | 38 + .../rest/types/v_1_audit_response.py | 28 + .../rest/types/v_1_audit_response_event.py | 50 + .../types/v_1_audit_response_event_request.py | 67 + .../types/v_1_batch_operation_response.py | 33 + .../generated/rest/types/v_1_batch_record.py | 69 + .../rest/types/v_1_bin_list_response.py | 27 + .../types/v_1_bulk_delete_record_response.py | 26 + .../types/v_1_bulk_get_record_response.py | 23 + skyflow/generated/rest/types/v_1_byot.py | 5 + skyflow/generated/rest/types/v_1_card.py | 68 + .../rest/types/v_1_delete_file_response.py | 27 + .../rest/types/v_1_delete_record_response.py | 27 + .../types/v_1_detokenize_record_request.py | 25 + .../types/v_1_detokenize_record_response.py | 38 + .../rest/types/v_1_detokenize_response.py | 23 + .../generated/rest/types/v_1_field_records.py | 31 + .../rest/types/v_1_file_av_scan_status.py | 18 + .../rest/types/v_1_get_auth_token_response.py | 33 + .../v_1_get_file_scan_status_response.py | 20 + .../rest/types/v_1_get_query_response.py | 23 + .../rest/types/v_1_insert_record_response.py | 23 + .../generated/rest/types/v_1_member_type.py | 5 + .../rest/types/v_1_record_meta_properties.py | 27 + .../rest/types/v_1_tokenize_record_request.py | 31 + .../types/v_1_tokenize_record_response.py | 22 + .../rest/types/v_1_tokenize_response.py | 23 + .../rest/types/v_1_update_record_response.py | 27 + .../rest/types/v_1_vault_field_mapping.py | 36 + .../rest/types/v_1_vault_schema_config.py | 34 + skyflow/generated/rest/version.py | 1 + skyflow/service_account/_utils.py | 4 +- skyflow/service_account/client/auth_client.py | 13 +- skyflow/utils/_utils.py | 5 +- skyflow/utils/constants.py | 2 + skyflow/utils/enums/env.py | 8 +- skyflow/utils/enums/redaction_type.py | 9 +- skyflow/utils/enums/token_mode.py | 7 +- skyflow/utils/validations/_validations.py | 16 +- skyflow/vault/client/client.py | 16 +- skyflow/vault/controller/_vault.py | 96 +- skyflow/vault/tokens/_detokenize_request.py | 2 - tests/client/test_skyflow.py | 4 +- tests/vault/client/test__client.py | 49 +- tests/vault/controller/test__vault.py | 228 +- 170 files changed, 7150 insertions(+), 12346 deletions(-) delete mode 100644 skyflow/generated/rest/api/__init__.py delete mode 100644 skyflow/generated/rest/api/audit_api.py delete mode 100644 skyflow/generated/rest/api/authentication_api.py delete mode 100644 skyflow/generated/rest/api/bin_lookup_api.py delete mode 100644 skyflow/generated/rest/api/query_api.py delete mode 100644 skyflow/generated/rest/api/records_api.py delete mode 100644 skyflow/generated/rest/api/tokens_api.py delete mode 100644 skyflow/generated/rest/api_client.py delete mode 100644 skyflow/generated/rest/api_response.py create mode 100644 skyflow/generated/rest/audit/__init__.py create mode 100644 skyflow/generated/rest/audit/client.py create mode 100644 skyflow/generated/rest/audit/types/__init__.py create mode 100644 skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_action_type.py create mode 100644 skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_access_type.py create mode 100644 skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_actor_type.py create mode 100644 skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_auth_mode.py create mode 100644 skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_resource_type.py create mode 100644 skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_sort_ops_order_by.py create mode 100644 skyflow/generated/rest/authentication/__init__.py create mode 100644 skyflow/generated/rest/authentication/client.py create mode 100644 skyflow/generated/rest/bin_lookup/__init__.py create mode 100644 skyflow/generated/rest/bin_lookup/client.py create mode 100644 skyflow/generated/rest/client.py delete mode 100644 skyflow/generated/rest/configuration.py create mode 100644 skyflow/generated/rest/core/__init__.py create mode 100644 skyflow/generated/rest/core/api_error.py create mode 100644 skyflow/generated/rest/core/client_wrapper.py create mode 100644 skyflow/generated/rest/core/datetime_utils.py create mode 100644 skyflow/generated/rest/core/file.py create mode 100644 skyflow/generated/rest/core/http_client.py create mode 100644 skyflow/generated/rest/core/jsonable_encoder.py create mode 100644 skyflow/generated/rest/core/pydantic_utilities.py create mode 100644 skyflow/generated/rest/core/query_encoder.py create mode 100644 skyflow/generated/rest/core/remove_none_from_dict.py create mode 100644 skyflow/generated/rest/core/request_options.py create mode 100644 skyflow/generated/rest/core/serialization.py create mode 100644 skyflow/generated/rest/environment.py create mode 100644 skyflow/generated/rest/errors/__init__.py create mode 100644 skyflow/generated/rest/errors/bad_request_error.py create mode 100644 skyflow/generated/rest/errors/not_found_error.py create mode 100644 skyflow/generated/rest/errors/unauthorized_error.py delete mode 100644 skyflow/generated/rest/exceptions.py delete mode 100644 skyflow/generated/rest/models/__init__.py delete mode 100644 skyflow/generated/rest/models/audit_event_audit_resource_type.py delete mode 100644 skyflow/generated/rest/models/audit_event_context.py delete mode 100644 skyflow/generated/rest/models/audit_event_data.py delete mode 100644 skyflow/generated/rest/models/audit_event_http_info.py delete mode 100644 skyflow/generated/rest/models/batch_record_method.py delete mode 100644 skyflow/generated/rest/models/context_access_type.py delete mode 100644 skyflow/generated/rest/models/context_auth_mode.py delete mode 100644 skyflow/generated/rest/models/detokenize_record_response_value_type.py delete mode 100644 skyflow/generated/rest/models/googlerpc_status.py delete mode 100644 skyflow/generated/rest/models/protobuf_any.py delete mode 100644 skyflow/generated/rest/models/query_service_execute_query_body.py delete mode 100644 skyflow/generated/rest/models/record_service_batch_operation_body.py delete mode 100644 skyflow/generated/rest/models/record_service_bulk_delete_record_body.py delete mode 100644 skyflow/generated/rest/models/record_service_insert_record_body.py delete mode 100644 skyflow/generated/rest/models/record_service_update_record_body.py delete mode 100644 skyflow/generated/rest/models/redaction_enum_redaction.py delete mode 100644 skyflow/generated/rest/models/request_action_type.py delete mode 100644 skyflow/generated/rest/models/v1_audit_after_options.py delete mode 100644 skyflow/generated/rest/models/v1_audit_event_response.py delete mode 100644 skyflow/generated/rest/models/v1_audit_response.py delete mode 100644 skyflow/generated/rest/models/v1_audit_response_event.py delete mode 100644 skyflow/generated/rest/models/v1_audit_response_event_request.py delete mode 100644 skyflow/generated/rest/models/v1_batch_operation_response.py delete mode 100644 skyflow/generated/rest/models/v1_batch_record.py delete mode 100644 skyflow/generated/rest/models/v1_bin_list_request.py delete mode 100644 skyflow/generated/rest/models/v1_bin_list_response.py delete mode 100644 skyflow/generated/rest/models/v1_bulk_delete_record_response.py delete mode 100644 skyflow/generated/rest/models/v1_bulk_get_record_response.py delete mode 100644 skyflow/generated/rest/models/v1_byot.py delete mode 100644 skyflow/generated/rest/models/v1_card.py delete mode 100644 skyflow/generated/rest/models/v1_delete_file_response.py delete mode 100644 skyflow/generated/rest/models/v1_delete_record_response.py delete mode 100644 skyflow/generated/rest/models/v1_detokenize_payload.py delete mode 100644 skyflow/generated/rest/models/v1_detokenize_record_request.py delete mode 100644 skyflow/generated/rest/models/v1_detokenize_record_response.py delete mode 100644 skyflow/generated/rest/models/v1_detokenize_response.py delete mode 100644 skyflow/generated/rest/models/v1_field_records.py delete mode 100644 skyflow/generated/rest/models/v1_file_av_scan_status.py delete mode 100644 skyflow/generated/rest/models/v1_get_auth_token_request.py delete mode 100644 skyflow/generated/rest/models/v1_get_auth_token_response.py delete mode 100644 skyflow/generated/rest/models/v1_get_file_scan_status_response.py delete mode 100644 skyflow/generated/rest/models/v1_get_query_response.py delete mode 100644 skyflow/generated/rest/models/v1_insert_record_response.py delete mode 100644 skyflow/generated/rest/models/v1_member_type.py delete mode 100644 skyflow/generated/rest/models/v1_record_meta_properties.py delete mode 100644 skyflow/generated/rest/models/v1_tokenize_payload.py delete mode 100644 skyflow/generated/rest/models/v1_tokenize_record_request.py delete mode 100644 skyflow/generated/rest/models/v1_tokenize_record_response.py delete mode 100644 skyflow/generated/rest/models/v1_tokenize_response.py delete mode 100644 skyflow/generated/rest/models/v1_update_record_response.py delete mode 100644 skyflow/generated/rest/models/v1_vault_field_mapping.py delete mode 100644 skyflow/generated/rest/models/v1_vault_schema_config.py create mode 100644 skyflow/generated/rest/query/__init__.py create mode 100644 skyflow/generated/rest/query/client.py create mode 100644 skyflow/generated/rest/records/__init__.py create mode 100644 skyflow/generated/rest/records/client.py create mode 100644 skyflow/generated/rest/records/types/__init__.py create mode 100644 skyflow/generated/rest/records/types/record_service_bulk_get_record_request_order_by.py create mode 100644 skyflow/generated/rest/records/types/record_service_bulk_get_record_request_redaction.py create mode 100644 skyflow/generated/rest/records/types/record_service_get_record_request_redaction.py delete mode 100644 skyflow/generated/rest/rest.py create mode 100644 skyflow/generated/rest/tokens/__init__.py create mode 100644 skyflow/generated/rest/tokens/client.py create mode 100644 skyflow/generated/rest/types/__init__.py create mode 100644 skyflow/generated/rest/types/audit_event_audit_resource_type.py create mode 100644 skyflow/generated/rest/types/audit_event_context.py create mode 100644 skyflow/generated/rest/types/audit_event_data.py create mode 100644 skyflow/generated/rest/types/audit_event_http_info.py create mode 100644 skyflow/generated/rest/types/batch_record_method.py create mode 100644 skyflow/generated/rest/types/context_access_type.py create mode 100644 skyflow/generated/rest/types/context_auth_mode.py create mode 100644 skyflow/generated/rest/types/detokenize_record_response_value_type.py create mode 100644 skyflow/generated/rest/types/googlerpc_status.py create mode 100644 skyflow/generated/rest/types/protobuf_any.py create mode 100644 skyflow/generated/rest/types/redaction_enum_redaction.py create mode 100644 skyflow/generated/rest/types/request_action_type.py create mode 100644 skyflow/generated/rest/types/v_1_audit_after_options.py create mode 100644 skyflow/generated/rest/types/v_1_audit_event_response.py create mode 100644 skyflow/generated/rest/types/v_1_audit_response.py create mode 100644 skyflow/generated/rest/types/v_1_audit_response_event.py create mode 100644 skyflow/generated/rest/types/v_1_audit_response_event_request.py create mode 100644 skyflow/generated/rest/types/v_1_batch_operation_response.py create mode 100644 skyflow/generated/rest/types/v_1_batch_record.py create mode 100644 skyflow/generated/rest/types/v_1_bin_list_response.py create mode 100644 skyflow/generated/rest/types/v_1_bulk_delete_record_response.py create mode 100644 skyflow/generated/rest/types/v_1_bulk_get_record_response.py create mode 100644 skyflow/generated/rest/types/v_1_byot.py create mode 100644 skyflow/generated/rest/types/v_1_card.py create mode 100644 skyflow/generated/rest/types/v_1_delete_file_response.py create mode 100644 skyflow/generated/rest/types/v_1_delete_record_response.py create mode 100644 skyflow/generated/rest/types/v_1_detokenize_record_request.py create mode 100644 skyflow/generated/rest/types/v_1_detokenize_record_response.py create mode 100644 skyflow/generated/rest/types/v_1_detokenize_response.py create mode 100644 skyflow/generated/rest/types/v_1_field_records.py create mode 100644 skyflow/generated/rest/types/v_1_file_av_scan_status.py create mode 100644 skyflow/generated/rest/types/v_1_get_auth_token_response.py create mode 100644 skyflow/generated/rest/types/v_1_get_file_scan_status_response.py create mode 100644 skyflow/generated/rest/types/v_1_get_query_response.py create mode 100644 skyflow/generated/rest/types/v_1_insert_record_response.py create mode 100644 skyflow/generated/rest/types/v_1_member_type.py create mode 100644 skyflow/generated/rest/types/v_1_record_meta_properties.py create mode 100644 skyflow/generated/rest/types/v_1_tokenize_record_request.py create mode 100644 skyflow/generated/rest/types/v_1_tokenize_record_response.py create mode 100644 skyflow/generated/rest/types/v_1_tokenize_response.py create mode 100644 skyflow/generated/rest/types/v_1_update_record_response.py create mode 100644 skyflow/generated/rest/types/v_1_vault_field_mapping.py create mode 100644 skyflow/generated/rest/types/v_1_vault_schema_config.py create mode 100644 skyflow/generated/rest/version.py create mode 100644 skyflow/utils/constants.py diff --git a/ci-scripts/bump_version.sh b/ci-scripts/bump_version.sh index a770e905..ab79e8aa 100755 --- a/ci-scripts/bump_version.sh +++ b/ci-scripts/bump_version.sh @@ -7,6 +7,7 @@ then sed -E "s/current_version = .+/current_version = '$SEMVER'/g" setup.py > tempfile && cat tempfile > setup.py && rm -f tempfile sed -E "s/SDK_VERSION = .+/SDK_VERSION = '$SEMVER'/g" skyflow/utils/_version.py > tempfile && cat tempfile > skyflow/utils/_version.py && rm -f tempfile + sed -E "s/__version__ = .+/__version__ = '$SEMVER'/g" skyflow/generated/rest/version.py > tempfile && cat tempfile > skyflow/generated/rest/version.py && rm -f tempfile echo -------------------------- echo "Done, Package now at $1" @@ -18,6 +19,7 @@ else sed -E "s/current_version = .+/current_version = '$DEV_VERSION'/g" setup.py > tempfile && cat tempfile > setup.py && rm -f tempfile sed -E "s/SDK_VERSION = .+/SDK_VERSION = '$DEV_VERSION'/g" skyflow/utils/_version.py > tempfile && cat tempfile > skyflow/utils/_version.py && rm -f tempfile + sed -E "s/__version__ = .+/__version__ = '$DEV_VERSION'/g" skyflow/generated/rest/version.py > tempfile && cat tempfile > skyflow/generated/rest/version.py && rm -f tempfile echo -------------------------- echo "Done, Package now at $DEV_VERSION" diff --git a/requirements.txt b/requirements.txt index 46a85940..687bfb9b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,4 +8,5 @@ PyJWT~=2.9.0 requests~=2.32.3 coverage cryptography -python-dotenv~=1.0.1 \ No newline at end of file +python-dotenv~=1.0.1 +httpx \ No newline at end of file diff --git a/setup.py b/setup.py index 9d68a420..10181764 100644 --- a/setup.py +++ b/setup.py @@ -20,17 +20,18 @@ description='Skyflow SDK for the Python programming language', long_description=open('README.rst').read(), install_requires=[ - 'python_dateutil >= 2.5.3', - 'setuptools >= 21.0.0', - 'urllib3 >= 1.25.3, < 2.1.0', - 'pydantic >= 2', - 'typing-extensions >= 4.7.1', - 'DateTime~=5.5', - 'PyJWT~=2.9.0', - 'requests~=2.32.3', - 'coverage', - 'cryptography', - 'python-dotenv~=1.0.1' -], - python_requires=">=3.8" + 'python_dateutil >= 2.5.3', + 'setuptools >= 21.0.0', + 'urllib3 >= 1.25.3, < 2.1.0', + 'pydantic >= 2', + 'typing-extensions >= 4.7.1', + 'DateTime~=5.5', + 'PyJWT~=2.9.0', + 'requests~=2.32.3', + 'coverage', + 'cryptography', + 'python-dotenv~=1.0.1', + 'httpx' + ], + python_requires=">=3.8", ) diff --git a/skyflow/client/skyflow.py b/skyflow/client/skyflow.py index be3f7d9a..1c87bcaa 100644 --- a/skyflow/client/skyflow.py +++ b/skyflow/client/skyflow.py @@ -2,7 +2,7 @@ from skyflow import LogLevel from skyflow.error import SkyflowError from skyflow.utils import SkyflowMessages -from skyflow.utils.logger import log_info, Logger, log_error +from skyflow.utils.logger import log_info, Logger from skyflow.utils.validations import validate_vault_config, validate_connection_config, validate_update_vault_config, \ validate_update_connection_config, validate_credentials, validate_log_level from skyflow.vault.client.client import VaultClient diff --git a/skyflow/generated/rest/__init__.py b/skyflow/generated/rest/__init__.py index 1544b853..5cacae7e 100644 --- a/skyflow/generated/rest/__init__.py +++ b/skyflow/generated/rest/__init__.py @@ -1,88 +1,133 @@ -# coding: utf-8 +# This file was auto-generated by Fern from our API Definition. -# flake8: noqa +from .types import ( + AuditEventAuditResourceType, + AuditEventContext, + AuditEventData, + AuditEventHttpInfo, + BatchRecordMethod, + ContextAccessType, + ContextAuthMode, + DetokenizeRecordResponseValueType, + GooglerpcStatus, + ProtobufAny, + RedactionEnumRedaction, + RequestActionType, + V1AuditAfterOptions, + V1AuditEventResponse, + V1AuditResponse, + V1AuditResponseEvent, + V1AuditResponseEventRequest, + V1BatchOperationResponse, + V1BatchRecord, + V1BinListResponse, + V1BulkDeleteRecordResponse, + V1BulkGetRecordResponse, + V1Byot, + V1Card, + V1DeleteFileResponse, + V1DeleteRecordResponse, + V1DetokenizeRecordRequest, + V1DetokenizeRecordResponse, + V1DetokenizeResponse, + V1FieldRecords, + V1FileAvScanStatus, + V1GetAuthTokenResponse, + V1GetFileScanStatusResponse, + V1GetQueryResponse, + V1InsertRecordResponse, + V1MemberType, + V1RecordMetaProperties, + V1TokenizeRecordRequest, + V1TokenizeRecordResponse, + V1TokenizeResponse, + V1UpdateRecordResponse, + V1VaultFieldMapping, + V1VaultSchemaConfig, +) +from .errors import BadRequestError, NotFoundError, UnauthorizedError +from . import audit, authentication, bin_lookup, query, records, tokens +from .audit import ( + AuditServiceListAuditEventsRequestFilterOpsActionType, + AuditServiceListAuditEventsRequestFilterOpsContextAccessType, + AuditServiceListAuditEventsRequestFilterOpsContextActorType, + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode, + AuditServiceListAuditEventsRequestFilterOpsResourceType, + AuditServiceListAuditEventsRequestSortOpsOrderBy, +) +from .client import AsyncSkyflow, Skyflow +from .environment import SkyflowEnvironment +from .records import ( + RecordServiceBulkGetRecordRequestOrderBy, + RecordServiceBulkGetRecordRequestRedaction, + RecordServiceGetRecordRequestRedaction, +) +from .version import __version__ -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 skyflow.generated.rest.api.audit_api import AuditApi -from skyflow.generated.rest.api.bin_lookup_api import BINLookupApi -from skyflow.generated.rest.api.query_api import QueryApi -from skyflow.generated.rest.api.records_api import RecordsApi -from skyflow.generated.rest.api.tokens_api import TokensApi - -# import ApiClient -from skyflow.generated.rest.api_response import ApiResponse -from skyflow.generated.rest.api_client import ApiClient -from skyflow.generated.rest.configuration import Configuration -from skyflow.generated.rest.exceptions import OpenApiException -from skyflow.generated.rest.exceptions import ApiTypeError -from skyflow.generated.rest.exceptions import ApiValueError -from skyflow.generated.rest.exceptions import ApiKeyError -from skyflow.generated.rest.exceptions import ApiAttributeError -from skyflow.generated.rest.exceptions import ApiException - -# import models into sdk package -from skyflow.generated.rest.models.audit_event_audit_resource_type import AuditEventAuditResourceType -from skyflow.generated.rest.models.audit_event_context import AuditEventContext -from skyflow.generated.rest.models.audit_event_data import AuditEventData -from skyflow.generated.rest.models.audit_event_http_info import AuditEventHTTPInfo -from skyflow.generated.rest.models.batch_record_method import BatchRecordMethod -from skyflow.generated.rest.models.context_access_type import ContextAccessType -from skyflow.generated.rest.models.context_auth_mode import ContextAuthMode -from skyflow.generated.rest.models.detokenize_record_response_value_type import DetokenizeRecordResponseValueType -from skyflow.generated.rest.models.googlerpc_status import GooglerpcStatus -from skyflow.generated.rest.models.protobuf_any import ProtobufAny -from skyflow.generated.rest.models.query_service_execute_query_body import QueryServiceExecuteQueryBody -from skyflow.generated.rest.models.record_service_batch_operation_body import RecordServiceBatchOperationBody -from skyflow.generated.rest.models.record_service_bulk_delete_record_body import RecordServiceBulkDeleteRecordBody -from skyflow.generated.rest.models.record_service_insert_record_body import RecordServiceInsertRecordBody -from skyflow.generated.rest.models.record_service_update_record_body import RecordServiceUpdateRecordBody -from skyflow.generated.rest.models.redaction_enum_redaction import RedactionEnumREDACTION -from skyflow.generated.rest.models.request_action_type import RequestActionType -from skyflow.generated.rest.models.v1_audit_after_options import V1AuditAfterOptions -from skyflow.generated.rest.models.v1_audit_event_response import V1AuditEventResponse -from skyflow.generated.rest.models.v1_audit_response import V1AuditResponse -from skyflow.generated.rest.models.v1_audit_response_event import V1AuditResponseEvent -from skyflow.generated.rest.models.v1_audit_response_event_request import V1AuditResponseEventRequest -from skyflow.generated.rest.models.v1_bin_list_request import V1BINListRequest -from skyflow.generated.rest.models.v1_bin_list_response import V1BINListResponse -from skyflow.generated.rest.models.v1_byot import V1BYOT -from skyflow.generated.rest.models.v1_batch_operation_response import V1BatchOperationResponse -from skyflow.generated.rest.models.v1_batch_record import V1BatchRecord -from skyflow.generated.rest.models.v1_bulk_delete_record_response import V1BulkDeleteRecordResponse -from skyflow.generated.rest.models.v1_bulk_get_record_response import V1BulkGetRecordResponse -from skyflow.generated.rest.models.v1_card import V1Card -from skyflow.generated.rest.models.v1_delete_file_response import V1DeleteFileResponse -from skyflow.generated.rest.models.v1_delete_record_response import V1DeleteRecordResponse -from skyflow.generated.rest.models.v1_detokenize_payload import V1DetokenizePayload -from skyflow.generated.rest.models.v1_detokenize_record_request import V1DetokenizeRecordRequest -from skyflow.generated.rest.models.v1_detokenize_record_response import V1DetokenizeRecordResponse -from skyflow.generated.rest.models.v1_detokenize_response import V1DetokenizeResponse -from skyflow.generated.rest.models.v1_field_records import V1FieldRecords -from skyflow.generated.rest.models.v1_file_av_scan_status import V1FileAVScanStatus -from skyflow.generated.rest.models.v1_get_file_scan_status_response import V1GetFileScanStatusResponse -from skyflow.generated.rest.models.v1_get_query_response import V1GetQueryResponse -from skyflow.generated.rest.models.v1_insert_record_response import V1InsertRecordResponse -from skyflow.generated.rest.models.v1_member_type import V1MemberType -from skyflow.generated.rest.models.v1_record_meta_properties import V1RecordMetaProperties -from skyflow.generated.rest.models.v1_tokenize_payload import V1TokenizePayload -from skyflow.generated.rest.models.v1_tokenize_record_request import V1TokenizeRecordRequest -from skyflow.generated.rest.models.v1_tokenize_record_response import V1TokenizeRecordResponse -from skyflow.generated.rest.models.v1_tokenize_response import V1TokenizeResponse -from skyflow.generated.rest.models.v1_update_record_response import V1UpdateRecordResponse -from skyflow.generated.rest.models.v1_vault_field_mapping import V1VaultFieldMapping -from skyflow.generated.rest.models.v1_vault_schema_config import V1VaultSchemaConfig +__all__ = [ + "AsyncSkyflow", + "AuditEventAuditResourceType", + "AuditEventContext", + "AuditEventData", + "AuditEventHttpInfo", + "AuditServiceListAuditEventsRequestFilterOpsActionType", + "AuditServiceListAuditEventsRequestFilterOpsContextAccessType", + "AuditServiceListAuditEventsRequestFilterOpsContextActorType", + "AuditServiceListAuditEventsRequestFilterOpsContextAuthMode", + "AuditServiceListAuditEventsRequestFilterOpsResourceType", + "AuditServiceListAuditEventsRequestSortOpsOrderBy", + "BadRequestError", + "BatchRecordMethod", + "ContextAccessType", + "ContextAuthMode", + "DetokenizeRecordResponseValueType", + "GooglerpcStatus", + "NotFoundError", + "ProtobufAny", + "RecordServiceBulkGetRecordRequestOrderBy", + "RecordServiceBulkGetRecordRequestRedaction", + "RecordServiceGetRecordRequestRedaction", + "RedactionEnumRedaction", + "RequestActionType", + "Skyflow", + "SkyflowEnvironment", + "UnauthorizedError", + "V1AuditAfterOptions", + "V1AuditEventResponse", + "V1AuditResponse", + "V1AuditResponseEvent", + "V1AuditResponseEventRequest", + "V1BatchOperationResponse", + "V1BatchRecord", + "V1BinListResponse", + "V1BulkDeleteRecordResponse", + "V1BulkGetRecordResponse", + "V1Byot", + "V1Card", + "V1DeleteFileResponse", + "V1DeleteRecordResponse", + "V1DetokenizeRecordRequest", + "V1DetokenizeRecordResponse", + "V1DetokenizeResponse", + "V1FieldRecords", + "V1FileAvScanStatus", + "V1GetAuthTokenResponse", + "V1GetFileScanStatusResponse", + "V1GetQueryResponse", + "V1InsertRecordResponse", + "V1MemberType", + "V1RecordMetaProperties", + "V1TokenizeRecordRequest", + "V1TokenizeRecordResponse", + "V1TokenizeResponse", + "V1UpdateRecordResponse", + "V1VaultFieldMapping", + "V1VaultSchemaConfig", + "__version__", + "audit", + "authentication", + "bin_lookup", + "query", + "records", + "tokens", +] diff --git a/skyflow/generated/rest/api/__init__.py b/skyflow/generated/rest/api/__init__.py deleted file mode 100644 index 01b15fdb..00000000 --- a/skyflow/generated/rest/api/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# flake8: noqa - -# import apis into api package -from skyflow.generated.rest.api.audit_api import AuditApi -from skyflow.generated.rest.api.bin_lookup_api import BINLookupApi -from skyflow.generated.rest.api.query_api import QueryApi -from skyflow.generated.rest.api.records_api import RecordsApi -from skyflow.generated.rest.api.tokens_api import TokensApi -from skyflow.generated.rest.api.authentication_api import AuthenticationApi diff --git a/skyflow/generated/rest/api/audit_api.py b/skyflow/generated/rest/api/audit_api.py deleted file mode 100644 index dc6de1fe..00000000 --- a/skyflow/generated/rest/api/audit_api.py +++ /dev/null @@ -1,848 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from pydantic import Field, StrictInt, StrictStr, field_validator -from typing import Optional -from typing_extensions import Annotated -from skyflow.generated.rest.models.v1_audit_response import V1AuditResponse - -from skyflow.generated.rest.api_client import ApiClient, RequestSerialized -from skyflow.generated.rest.api_response import ApiResponse -from skyflow.generated.rest.rest import RESTResponseType - - -class AuditApi: - """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 - def audit_service_list_audit_events( - self, - filter_ops_account_id: Annotated[StrictStr, Field(description="Resources with the specified account ID.")], - filter_ops_context_change_id: Annotated[Optional[StrictStr], Field(description="ID for the audit event.")] = None, - filter_ops_context_request_id: Annotated[Optional[StrictStr], Field(description="ID for the request that caused the event.")] = None, - filter_ops_context_trace_id: Annotated[Optional[StrictStr], Field(description="ID for the request set by the service that received the request.")] = None, - filter_ops_context_session_id: Annotated[Optional[StrictStr], Field(description="ID for the session in which the request was sent.")] = None, - filter_ops_context_actor: Annotated[Optional[StrictStr], Field(description="Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID.")] = None, - filter_ops_context_actor_type: Annotated[Optional[StrictStr], Field(description="Type of member who sent the request.")] = None, - filter_ops_context_access_type: Annotated[Optional[StrictStr], Field(description="Type of access for the request.")] = None, - filter_ops_context_ip_address: Annotated[Optional[StrictStr], Field(description="IP Address of the client that made the request.")] = None, - filter_ops_context_origin: Annotated[Optional[StrictStr], Field(description="HTTP Origin request header (including scheme, hostname, and port) of the request.")] = None, - filter_ops_context_auth_mode: Annotated[Optional[StrictStr], Field(description="Authentication mode the `actor` used.")] = None, - filter_ops_context_jwt_id: Annotated[Optional[StrictStr], Field(description="ID of the JWT token.")] = None, - filter_ops_context_bearer_token_context_id: Annotated[Optional[StrictStr], Field(description="Embedded User Context.")] = None, - filter_ops_parent_account_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified parent account ID.")] = None, - filter_ops_workspace_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified workspace ID.")] = None, - filter_ops_vault_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified vault ID.")] = None, - filter_ops_resource_ids: Annotated[Optional[StrictStr], Field(description="Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\/\\\". For example, \"VAULT/12345, USER/67890\".")] = None, - filter_ops_action_type: Annotated[Optional[StrictStr], Field(description="Events with the specified action type.")] = None, - filter_ops_resource_type: Annotated[Optional[StrictStr], Field(description="Resources with the specified type.")] = None, - filter_ops_tags: Annotated[Optional[StrictStr], Field(description="Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\".")] = None, - filter_ops_response_code: Annotated[Optional[StrictInt], Field(description="HTTP response code of the request.")] = None, - filter_ops_start_time: Annotated[Optional[StrictStr], Field(description="Start timestamp for the query, in SQL format.")] = None, - filter_ops_end_time: Annotated[Optional[StrictStr], Field(description="End timestamp for the query, in SQL format.")] = None, - filter_ops_api_name: Annotated[Optional[StrictStr], Field(description="Name of the API called in the request.")] = None, - filter_ops_response_message: Annotated[Optional[StrictStr], Field(description="Response message of the request.")] = None, - filter_ops_http_method: Annotated[Optional[StrictStr], Field(description="HTTP method of the request.")] = None, - filter_ops_http_uri: Annotated[Optional[StrictStr], Field(description="HTTP URI of the request.")] = None, - sort_ops_sort_by: Annotated[Optional[StrictStr], Field(description="Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\").")] = None, - sort_ops_order_by: Annotated[Optional[StrictStr], Field(description="Ascending or descending ordering of results.")] = None, - after_ops_timestamp: Annotated[Optional[StrictStr], Field(description="Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.")] = None, - after_ops_change_id: Annotated[Optional[StrictStr], Field(description="Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.")] = None, - limit: Annotated[Optional[StrictInt], Field(description="Number of results to return.")] = None, - offset: Annotated[Optional[StrictInt], Field(description="Record position at which to start returning results.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1AuditResponse: - """List Audit Events - - Lists audit events that match query parameters. - - :param filter_ops_account_id: Resources with the specified account ID. (required) - :type filter_ops_account_id: str - :param filter_ops_context_change_id: ID for the audit event. - :type filter_ops_context_change_id: str - :param filter_ops_context_request_id: ID for the request that caused the event. - :type filter_ops_context_request_id: str - :param filter_ops_context_trace_id: ID for the request set by the service that received the request. - :type filter_ops_context_trace_id: str - :param filter_ops_context_session_id: ID for the session in which the request was sent. - :type filter_ops_context_session_id: str - :param filter_ops_context_actor: Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. - :type filter_ops_context_actor: str - :param filter_ops_context_actor_type: Type of member who sent the request. - :type filter_ops_context_actor_type: str - :param filter_ops_context_access_type: Type of access for the request. - :type filter_ops_context_access_type: str - :param filter_ops_context_ip_address: IP Address of the client that made the request. - :type filter_ops_context_ip_address: str - :param filter_ops_context_origin: HTTP Origin request header (including scheme, hostname, and port) of the request. - :type filter_ops_context_origin: str - :param filter_ops_context_auth_mode: Authentication mode the `actor` used. - :type filter_ops_context_auth_mode: str - :param filter_ops_context_jwt_id: ID of the JWT token. - :type filter_ops_context_jwt_id: str - :param filter_ops_context_bearer_token_context_id: Embedded User Context. - :type filter_ops_context_bearer_token_context_id: str - :param filter_ops_parent_account_id: Resources with the specified parent account ID. - :type filter_ops_parent_account_id: str - :param filter_ops_workspace_id: Resources with the specified workspace ID. - :type filter_ops_workspace_id: str - :param filter_ops_vault_id: Resources with the specified vault ID. - :type filter_ops_vault_id: str - :param filter_ops_resource_ids: Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\/\\\". For example, \"VAULT/12345, USER/67890\". - :type filter_ops_resource_ids: str - :param filter_ops_action_type: Events with the specified action type. - :type filter_ops_action_type: str - :param filter_ops_resource_type: Resources with the specified type. - :type filter_ops_resource_type: str - :param filter_ops_tags: Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". - :type filter_ops_tags: str - :param filter_ops_response_code: HTTP response code of the request. - :type filter_ops_response_code: int - :param filter_ops_start_time: Start timestamp for the query, in SQL format. - :type filter_ops_start_time: str - :param filter_ops_end_time: End timestamp for the query, in SQL format. - :type filter_ops_end_time: str - :param filter_ops_api_name: Name of the API called in the request. - :type filter_ops_api_name: str - :param filter_ops_response_message: Response message of the request. - :type filter_ops_response_message: str - :param filter_ops_http_method: HTTP method of the request. - :type filter_ops_http_method: str - :param filter_ops_http_uri: HTTP URI of the request. - :type filter_ops_http_uri: str - :param sort_ops_sort_by: Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). - :type sort_ops_sort_by: str - :param sort_ops_order_by: Ascending or descending ordering of results. - :type sort_ops_order_by: str - :param after_ops_timestamp: Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - :type after_ops_timestamp: str - :param after_ops_change_id: Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - :type after_ops_change_id: str - :param limit: Number of results to return. - :type limit: int - :param offset: Record position at which to start returning results. - :type offset: int - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._audit_service_list_audit_events_serialize( - filter_ops_account_id=filter_ops_account_id, - filter_ops_context_change_id=filter_ops_context_change_id, - filter_ops_context_request_id=filter_ops_context_request_id, - filter_ops_context_trace_id=filter_ops_context_trace_id, - filter_ops_context_session_id=filter_ops_context_session_id, - filter_ops_context_actor=filter_ops_context_actor, - filter_ops_context_actor_type=filter_ops_context_actor_type, - filter_ops_context_access_type=filter_ops_context_access_type, - filter_ops_context_ip_address=filter_ops_context_ip_address, - filter_ops_context_origin=filter_ops_context_origin, - filter_ops_context_auth_mode=filter_ops_context_auth_mode, - filter_ops_context_jwt_id=filter_ops_context_jwt_id, - filter_ops_context_bearer_token_context_id=filter_ops_context_bearer_token_context_id, - filter_ops_parent_account_id=filter_ops_parent_account_id, - filter_ops_workspace_id=filter_ops_workspace_id, - filter_ops_vault_id=filter_ops_vault_id, - filter_ops_resource_ids=filter_ops_resource_ids, - filter_ops_action_type=filter_ops_action_type, - filter_ops_resource_type=filter_ops_resource_type, - filter_ops_tags=filter_ops_tags, - filter_ops_response_code=filter_ops_response_code, - filter_ops_start_time=filter_ops_start_time, - filter_ops_end_time=filter_ops_end_time, - filter_ops_api_name=filter_ops_api_name, - filter_ops_response_message=filter_ops_response_message, - filter_ops_http_method=filter_ops_http_method, - filter_ops_http_uri=filter_ops_http_uri, - sort_ops_sort_by=sort_ops_sort_by, - sort_ops_order_by=sort_ops_order_by, - after_ops_timestamp=after_ops_timestamp, - after_ops_change_id=after_ops_change_id, - limit=limit, - offset=offset, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1AuditResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def audit_service_list_audit_events_with_http_info( - self, - filter_ops_account_id: Annotated[StrictStr, Field(description="Resources with the specified account ID.")], - filter_ops_context_change_id: Annotated[Optional[StrictStr], Field(description="ID for the audit event.")] = None, - filter_ops_context_request_id: Annotated[Optional[StrictStr], Field(description="ID for the request that caused the event.")] = None, - filter_ops_context_trace_id: Annotated[Optional[StrictStr], Field(description="ID for the request set by the service that received the request.")] = None, - filter_ops_context_session_id: Annotated[Optional[StrictStr], Field(description="ID for the session in which the request was sent.")] = None, - filter_ops_context_actor: Annotated[Optional[StrictStr], Field(description="Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID.")] = None, - filter_ops_context_actor_type: Annotated[Optional[StrictStr], Field(description="Type of member who sent the request.")] = None, - filter_ops_context_access_type: Annotated[Optional[StrictStr], Field(description="Type of access for the request.")] = None, - filter_ops_context_ip_address: Annotated[Optional[StrictStr], Field(description="IP Address of the client that made the request.")] = None, - filter_ops_context_origin: Annotated[Optional[StrictStr], Field(description="HTTP Origin request header (including scheme, hostname, and port) of the request.")] = None, - filter_ops_context_auth_mode: Annotated[Optional[StrictStr], Field(description="Authentication mode the `actor` used.")] = None, - filter_ops_context_jwt_id: Annotated[Optional[StrictStr], Field(description="ID of the JWT token.")] = None, - filter_ops_context_bearer_token_context_id: Annotated[Optional[StrictStr], Field(description="Embedded User Context.")] = None, - filter_ops_parent_account_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified parent account ID.")] = None, - filter_ops_workspace_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified workspace ID.")] = None, - filter_ops_vault_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified vault ID.")] = None, - filter_ops_resource_ids: Annotated[Optional[StrictStr], Field(description="Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\/\\\". For example, \"VAULT/12345, USER/67890\".")] = None, - filter_ops_action_type: Annotated[Optional[StrictStr], Field(description="Events with the specified action type.")] = None, - filter_ops_resource_type: Annotated[Optional[StrictStr], Field(description="Resources with the specified type.")] = None, - filter_ops_tags: Annotated[Optional[StrictStr], Field(description="Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\".")] = None, - filter_ops_response_code: Annotated[Optional[StrictInt], Field(description="HTTP response code of the request.")] = None, - filter_ops_start_time: Annotated[Optional[StrictStr], Field(description="Start timestamp for the query, in SQL format.")] = None, - filter_ops_end_time: Annotated[Optional[StrictStr], Field(description="End timestamp for the query, in SQL format.")] = None, - filter_ops_api_name: Annotated[Optional[StrictStr], Field(description="Name of the API called in the request.")] = None, - filter_ops_response_message: Annotated[Optional[StrictStr], Field(description="Response message of the request.")] = None, - filter_ops_http_method: Annotated[Optional[StrictStr], Field(description="HTTP method of the request.")] = None, - filter_ops_http_uri: Annotated[Optional[StrictStr], Field(description="HTTP URI of the request.")] = None, - sort_ops_sort_by: Annotated[Optional[StrictStr], Field(description="Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\").")] = None, - sort_ops_order_by: Annotated[Optional[StrictStr], Field(description="Ascending or descending ordering of results.")] = None, - after_ops_timestamp: Annotated[Optional[StrictStr], Field(description="Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.")] = None, - after_ops_change_id: Annotated[Optional[StrictStr], Field(description="Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.")] = None, - limit: Annotated[Optional[StrictInt], Field(description="Number of results to return.")] = None, - offset: Annotated[Optional[StrictInt], Field(description="Record position at which to start returning results.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1AuditResponse]: - """List Audit Events - - Lists audit events that match query parameters. - - :param filter_ops_account_id: Resources with the specified account ID. (required) - :type filter_ops_account_id: str - :param filter_ops_context_change_id: ID for the audit event. - :type filter_ops_context_change_id: str - :param filter_ops_context_request_id: ID for the request that caused the event. - :type filter_ops_context_request_id: str - :param filter_ops_context_trace_id: ID for the request set by the service that received the request. - :type filter_ops_context_trace_id: str - :param filter_ops_context_session_id: ID for the session in which the request was sent. - :type filter_ops_context_session_id: str - :param filter_ops_context_actor: Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. - :type filter_ops_context_actor: str - :param filter_ops_context_actor_type: Type of member who sent the request. - :type filter_ops_context_actor_type: str - :param filter_ops_context_access_type: Type of access for the request. - :type filter_ops_context_access_type: str - :param filter_ops_context_ip_address: IP Address of the client that made the request. - :type filter_ops_context_ip_address: str - :param filter_ops_context_origin: HTTP Origin request header (including scheme, hostname, and port) of the request. - :type filter_ops_context_origin: str - :param filter_ops_context_auth_mode: Authentication mode the `actor` used. - :type filter_ops_context_auth_mode: str - :param filter_ops_context_jwt_id: ID of the JWT token. - :type filter_ops_context_jwt_id: str - :param filter_ops_context_bearer_token_context_id: Embedded User Context. - :type filter_ops_context_bearer_token_context_id: str - :param filter_ops_parent_account_id: Resources with the specified parent account ID. - :type filter_ops_parent_account_id: str - :param filter_ops_workspace_id: Resources with the specified workspace ID. - :type filter_ops_workspace_id: str - :param filter_ops_vault_id: Resources with the specified vault ID. - :type filter_ops_vault_id: str - :param filter_ops_resource_ids: Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\/\\\". For example, \"VAULT/12345, USER/67890\". - :type filter_ops_resource_ids: str - :param filter_ops_action_type: Events with the specified action type. - :type filter_ops_action_type: str - :param filter_ops_resource_type: Resources with the specified type. - :type filter_ops_resource_type: str - :param filter_ops_tags: Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". - :type filter_ops_tags: str - :param filter_ops_response_code: HTTP response code of the request. - :type filter_ops_response_code: int - :param filter_ops_start_time: Start timestamp for the query, in SQL format. - :type filter_ops_start_time: str - :param filter_ops_end_time: End timestamp for the query, in SQL format. - :type filter_ops_end_time: str - :param filter_ops_api_name: Name of the API called in the request. - :type filter_ops_api_name: str - :param filter_ops_response_message: Response message of the request. - :type filter_ops_response_message: str - :param filter_ops_http_method: HTTP method of the request. - :type filter_ops_http_method: str - :param filter_ops_http_uri: HTTP URI of the request. - :type filter_ops_http_uri: str - :param sort_ops_sort_by: Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). - :type sort_ops_sort_by: str - :param sort_ops_order_by: Ascending or descending ordering of results. - :type sort_ops_order_by: str - :param after_ops_timestamp: Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - :type after_ops_timestamp: str - :param after_ops_change_id: Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - :type after_ops_change_id: str - :param limit: Number of results to return. - :type limit: int - :param offset: Record position at which to start returning results. - :type offset: int - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._audit_service_list_audit_events_serialize( - filter_ops_account_id=filter_ops_account_id, - filter_ops_context_change_id=filter_ops_context_change_id, - filter_ops_context_request_id=filter_ops_context_request_id, - filter_ops_context_trace_id=filter_ops_context_trace_id, - filter_ops_context_session_id=filter_ops_context_session_id, - filter_ops_context_actor=filter_ops_context_actor, - filter_ops_context_actor_type=filter_ops_context_actor_type, - filter_ops_context_access_type=filter_ops_context_access_type, - filter_ops_context_ip_address=filter_ops_context_ip_address, - filter_ops_context_origin=filter_ops_context_origin, - filter_ops_context_auth_mode=filter_ops_context_auth_mode, - filter_ops_context_jwt_id=filter_ops_context_jwt_id, - filter_ops_context_bearer_token_context_id=filter_ops_context_bearer_token_context_id, - filter_ops_parent_account_id=filter_ops_parent_account_id, - filter_ops_workspace_id=filter_ops_workspace_id, - filter_ops_vault_id=filter_ops_vault_id, - filter_ops_resource_ids=filter_ops_resource_ids, - filter_ops_action_type=filter_ops_action_type, - filter_ops_resource_type=filter_ops_resource_type, - filter_ops_tags=filter_ops_tags, - filter_ops_response_code=filter_ops_response_code, - filter_ops_start_time=filter_ops_start_time, - filter_ops_end_time=filter_ops_end_time, - filter_ops_api_name=filter_ops_api_name, - filter_ops_response_message=filter_ops_response_message, - filter_ops_http_method=filter_ops_http_method, - filter_ops_http_uri=filter_ops_http_uri, - sort_ops_sort_by=sort_ops_sort_by, - sort_ops_order_by=sort_ops_order_by, - after_ops_timestamp=after_ops_timestamp, - after_ops_change_id=after_ops_change_id, - limit=limit, - offset=offset, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1AuditResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def audit_service_list_audit_events_without_preload_content( - self, - filter_ops_account_id: Annotated[StrictStr, Field(description="Resources with the specified account ID.")], - filter_ops_context_change_id: Annotated[Optional[StrictStr], Field(description="ID for the audit event.")] = None, - filter_ops_context_request_id: Annotated[Optional[StrictStr], Field(description="ID for the request that caused the event.")] = None, - filter_ops_context_trace_id: Annotated[Optional[StrictStr], Field(description="ID for the request set by the service that received the request.")] = None, - filter_ops_context_session_id: Annotated[Optional[StrictStr], Field(description="ID for the session in which the request was sent.")] = None, - filter_ops_context_actor: Annotated[Optional[StrictStr], Field(description="Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID.")] = None, - filter_ops_context_actor_type: Annotated[Optional[StrictStr], Field(description="Type of member who sent the request.")] = None, - filter_ops_context_access_type: Annotated[Optional[StrictStr], Field(description="Type of access for the request.")] = None, - filter_ops_context_ip_address: Annotated[Optional[StrictStr], Field(description="IP Address of the client that made the request.")] = None, - filter_ops_context_origin: Annotated[Optional[StrictStr], Field(description="HTTP Origin request header (including scheme, hostname, and port) of the request.")] = None, - filter_ops_context_auth_mode: Annotated[Optional[StrictStr], Field(description="Authentication mode the `actor` used.")] = None, - filter_ops_context_jwt_id: Annotated[Optional[StrictStr], Field(description="ID of the JWT token.")] = None, - filter_ops_context_bearer_token_context_id: Annotated[Optional[StrictStr], Field(description="Embedded User Context.")] = None, - filter_ops_parent_account_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified parent account ID.")] = None, - filter_ops_workspace_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified workspace ID.")] = None, - filter_ops_vault_id: Annotated[Optional[StrictStr], Field(description="Resources with the specified vault ID.")] = None, - filter_ops_resource_ids: Annotated[Optional[StrictStr], Field(description="Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\/\\\". For example, \"VAULT/12345, USER/67890\".")] = None, - filter_ops_action_type: Annotated[Optional[StrictStr], Field(description="Events with the specified action type.")] = None, - filter_ops_resource_type: Annotated[Optional[StrictStr], Field(description="Resources with the specified type.")] = None, - filter_ops_tags: Annotated[Optional[StrictStr], Field(description="Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\".")] = None, - filter_ops_response_code: Annotated[Optional[StrictInt], Field(description="HTTP response code of the request.")] = None, - filter_ops_start_time: Annotated[Optional[StrictStr], Field(description="Start timestamp for the query, in SQL format.")] = None, - filter_ops_end_time: Annotated[Optional[StrictStr], Field(description="End timestamp for the query, in SQL format.")] = None, - filter_ops_api_name: Annotated[Optional[StrictStr], Field(description="Name of the API called in the request.")] = None, - filter_ops_response_message: Annotated[Optional[StrictStr], Field(description="Response message of the request.")] = None, - filter_ops_http_method: Annotated[Optional[StrictStr], Field(description="HTTP method of the request.")] = None, - filter_ops_http_uri: Annotated[Optional[StrictStr], Field(description="HTTP URI of the request.")] = None, - sort_ops_sort_by: Annotated[Optional[StrictStr], Field(description="Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\").")] = None, - sort_ops_order_by: Annotated[Optional[StrictStr], Field(description="Ascending or descending ordering of results.")] = None, - after_ops_timestamp: Annotated[Optional[StrictStr], Field(description="Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.")] = None, - after_ops_change_id: Annotated[Optional[StrictStr], Field(description="Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.")] = None, - limit: Annotated[Optional[StrictInt], Field(description="Number of results to return.")] = None, - offset: Annotated[Optional[StrictInt], Field(description="Record position at which to start returning results.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """List Audit Events - - Lists audit events that match query parameters. - - :param filter_ops_account_id: Resources with the specified account ID. (required) - :type filter_ops_account_id: str - :param filter_ops_context_change_id: ID for the audit event. - :type filter_ops_context_change_id: str - :param filter_ops_context_request_id: ID for the request that caused the event. - :type filter_ops_context_request_id: str - :param filter_ops_context_trace_id: ID for the request set by the service that received the request. - :type filter_ops_context_trace_id: str - :param filter_ops_context_session_id: ID for the session in which the request was sent. - :type filter_ops_context_session_id: str - :param filter_ops_context_actor: Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. - :type filter_ops_context_actor: str - :param filter_ops_context_actor_type: Type of member who sent the request. - :type filter_ops_context_actor_type: str - :param filter_ops_context_access_type: Type of access for the request. - :type filter_ops_context_access_type: str - :param filter_ops_context_ip_address: IP Address of the client that made the request. - :type filter_ops_context_ip_address: str - :param filter_ops_context_origin: HTTP Origin request header (including scheme, hostname, and port) of the request. - :type filter_ops_context_origin: str - :param filter_ops_context_auth_mode: Authentication mode the `actor` used. - :type filter_ops_context_auth_mode: str - :param filter_ops_context_jwt_id: ID of the JWT token. - :type filter_ops_context_jwt_id: str - :param filter_ops_context_bearer_token_context_id: Embedded User Context. - :type filter_ops_context_bearer_token_context_id: str - :param filter_ops_parent_account_id: Resources with the specified parent account ID. - :type filter_ops_parent_account_id: str - :param filter_ops_workspace_id: Resources with the specified workspace ID. - :type filter_ops_workspace_id: str - :param filter_ops_vault_id: Resources with the specified vault ID. - :type filter_ops_vault_id: str - :param filter_ops_resource_ids: Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\/\\\". For example, \"VAULT/12345, USER/67890\". - :type filter_ops_resource_ids: str - :param filter_ops_action_type: Events with the specified action type. - :type filter_ops_action_type: str - :param filter_ops_resource_type: Resources with the specified type. - :type filter_ops_resource_type: str - :param filter_ops_tags: Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". - :type filter_ops_tags: str - :param filter_ops_response_code: HTTP response code of the request. - :type filter_ops_response_code: int - :param filter_ops_start_time: Start timestamp for the query, in SQL format. - :type filter_ops_start_time: str - :param filter_ops_end_time: End timestamp for the query, in SQL format. - :type filter_ops_end_time: str - :param filter_ops_api_name: Name of the API called in the request. - :type filter_ops_api_name: str - :param filter_ops_response_message: Response message of the request. - :type filter_ops_response_message: str - :param filter_ops_http_method: HTTP method of the request. - :type filter_ops_http_method: str - :param filter_ops_http_uri: HTTP URI of the request. - :type filter_ops_http_uri: str - :param sort_ops_sort_by: Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). - :type sort_ops_sort_by: str - :param sort_ops_order_by: Ascending or descending ordering of results. - :type sort_ops_order_by: str - :param after_ops_timestamp: Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - :type after_ops_timestamp: str - :param after_ops_change_id: Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - :type after_ops_change_id: str - :param limit: Number of results to return. - :type limit: int - :param offset: Record position at which to start returning results. - :type offset: int - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._audit_service_list_audit_events_serialize( - filter_ops_account_id=filter_ops_account_id, - filter_ops_context_change_id=filter_ops_context_change_id, - filter_ops_context_request_id=filter_ops_context_request_id, - filter_ops_context_trace_id=filter_ops_context_trace_id, - filter_ops_context_session_id=filter_ops_context_session_id, - filter_ops_context_actor=filter_ops_context_actor, - filter_ops_context_actor_type=filter_ops_context_actor_type, - filter_ops_context_access_type=filter_ops_context_access_type, - filter_ops_context_ip_address=filter_ops_context_ip_address, - filter_ops_context_origin=filter_ops_context_origin, - filter_ops_context_auth_mode=filter_ops_context_auth_mode, - filter_ops_context_jwt_id=filter_ops_context_jwt_id, - filter_ops_context_bearer_token_context_id=filter_ops_context_bearer_token_context_id, - filter_ops_parent_account_id=filter_ops_parent_account_id, - filter_ops_workspace_id=filter_ops_workspace_id, - filter_ops_vault_id=filter_ops_vault_id, - filter_ops_resource_ids=filter_ops_resource_ids, - filter_ops_action_type=filter_ops_action_type, - filter_ops_resource_type=filter_ops_resource_type, - filter_ops_tags=filter_ops_tags, - filter_ops_response_code=filter_ops_response_code, - filter_ops_start_time=filter_ops_start_time, - filter_ops_end_time=filter_ops_end_time, - filter_ops_api_name=filter_ops_api_name, - filter_ops_response_message=filter_ops_response_message, - filter_ops_http_method=filter_ops_http_method, - filter_ops_http_uri=filter_ops_http_uri, - sort_ops_sort_by=sort_ops_sort_by, - sort_ops_order_by=sort_ops_order_by, - after_ops_timestamp=after_ops_timestamp, - after_ops_change_id=after_ops_change_id, - limit=limit, - offset=offset, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1AuditResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _audit_service_list_audit_events_serialize( - self, - filter_ops_account_id, - filter_ops_context_change_id, - filter_ops_context_request_id, - filter_ops_context_trace_id, - filter_ops_context_session_id, - filter_ops_context_actor, - filter_ops_context_actor_type, - filter_ops_context_access_type, - filter_ops_context_ip_address, - filter_ops_context_origin, - filter_ops_context_auth_mode, - filter_ops_context_jwt_id, - filter_ops_context_bearer_token_context_id, - filter_ops_parent_account_id, - filter_ops_workspace_id, - filter_ops_vault_id, - filter_ops_resource_ids, - filter_ops_action_type, - filter_ops_resource_type, - filter_ops_tags, - filter_ops_response_code, - filter_ops_start_time, - filter_ops_end_time, - filter_ops_api_name, - filter_ops_response_message, - filter_ops_http_method, - filter_ops_http_uri, - sort_ops_sort_by, - sort_ops_order_by, - after_ops_timestamp, - after_ops_change_id, - limit, - offset, - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - if filter_ops_context_change_id is not None: - - _query_params.append(('filterOps.context.changeID', filter_ops_context_change_id)) - - if filter_ops_context_request_id is not None: - - _query_params.append(('filterOps.context.requestID', filter_ops_context_request_id)) - - if filter_ops_context_trace_id is not None: - - _query_params.append(('filterOps.context.traceID', filter_ops_context_trace_id)) - - if filter_ops_context_session_id is not None: - - _query_params.append(('filterOps.context.sessionID', filter_ops_context_session_id)) - - if filter_ops_context_actor is not None: - - _query_params.append(('filterOps.context.actor', filter_ops_context_actor)) - - if filter_ops_context_actor_type is not None: - - _query_params.append(('filterOps.context.actorType', filter_ops_context_actor_type)) - - if filter_ops_context_access_type is not None: - - _query_params.append(('filterOps.context.accessType', filter_ops_context_access_type)) - - if filter_ops_context_ip_address is not None: - - _query_params.append(('filterOps.context.ipAddress', filter_ops_context_ip_address)) - - if filter_ops_context_origin is not None: - - _query_params.append(('filterOps.context.origin', filter_ops_context_origin)) - - if filter_ops_context_auth_mode is not None: - - _query_params.append(('filterOps.context.authMode', filter_ops_context_auth_mode)) - - if filter_ops_context_jwt_id is not None: - - _query_params.append(('filterOps.context.jwtID', filter_ops_context_jwt_id)) - - if filter_ops_context_bearer_token_context_id is not None: - - _query_params.append(('filterOps.context.bearerTokenContextID', filter_ops_context_bearer_token_context_id)) - - if filter_ops_parent_account_id is not None: - - _query_params.append(('filterOps.parentAccountID', filter_ops_parent_account_id)) - - if filter_ops_account_id is not None: - - _query_params.append(('filterOps.accountID', filter_ops_account_id)) - - if filter_ops_workspace_id is not None: - - _query_params.append(('filterOps.workspaceID', filter_ops_workspace_id)) - - if filter_ops_vault_id is not None: - - _query_params.append(('filterOps.vaultID', filter_ops_vault_id)) - - if filter_ops_resource_ids is not None: - - _query_params.append(('filterOps.resourceIDs', filter_ops_resource_ids)) - - if filter_ops_action_type is not None: - - _query_params.append(('filterOps.actionType', filter_ops_action_type)) - - if filter_ops_resource_type is not None: - - _query_params.append(('filterOps.resourceType', filter_ops_resource_type)) - - if filter_ops_tags is not None: - - _query_params.append(('filterOps.tags', filter_ops_tags)) - - if filter_ops_response_code is not None: - - _query_params.append(('filterOps.responseCode', filter_ops_response_code)) - - if filter_ops_start_time is not None: - - _query_params.append(('filterOps.startTime', filter_ops_start_time)) - - if filter_ops_end_time is not None: - - _query_params.append(('filterOps.endTime', filter_ops_end_time)) - - if filter_ops_api_name is not None: - - _query_params.append(('filterOps.apiName', filter_ops_api_name)) - - if filter_ops_response_message is not None: - - _query_params.append(('filterOps.responseMessage', filter_ops_response_message)) - - if filter_ops_http_method is not None: - - _query_params.append(('filterOps.httpMethod', filter_ops_http_method)) - - if filter_ops_http_uri is not None: - - _query_params.append(('filterOps.httpURI', filter_ops_http_uri)) - - if sort_ops_sort_by is not None: - - _query_params.append(('sortOps.sortBy', sort_ops_sort_by)) - - if sort_ops_order_by is not None: - - _query_params.append(('sortOps.orderBy', sort_ops_order_by)) - - if after_ops_timestamp is not None: - - _query_params.append(('afterOps.timestamp', after_ops_timestamp)) - - if after_ops_change_id is not None: - - _query_params.append(('afterOps.changeID', after_ops_change_id)) - - if limit is not None: - - _query_params.append(('limit', limit)) - - if offset is not None: - - _query_params.append(('offset', offset)) - - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/v1/audit/events', - 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/skyflow/generated/rest/api/authentication_api.py b/skyflow/generated/rest/api/authentication_api.py deleted file mode 100644 index 8abbbf67..00000000 --- a/skyflow/generated/rest/api/authentication_api.py +++ /dev/null @@ -1,319 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Management API - - # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from skyflow.generated.rest.models.v1_get_auth_token_request import V1GetAuthTokenRequest -from skyflow.generated.rest.models.v1_get_auth_token_response import V1GetAuthTokenResponse - -from skyflow.generated.rest.api_client import ApiClient, RequestSerialized -from skyflow.generated.rest.api_response import ApiResponse -from skyflow.generated.rest.rest import RESTResponseType - - -class AuthenticationApi: - """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 - def authentication_service_get_auth_token( - self, - body: V1GetAuthTokenRequest, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1GetAuthTokenResponse: - """Get Bearer Token - -

Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the Authorization header.

Note: For recommended ways to authenticate, see API authentication.

- - :param body: (required) - :type body: V1GetAuthTokenRequest - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._authentication_service_get_auth_token_serialize( - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetAuthTokenResponse", - '400': "object", - '401': "object", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def authentication_service_get_auth_token_with_http_info( - self, - body: V1GetAuthTokenRequest, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1GetAuthTokenResponse]: - """Get Bearer Token - -

Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the Authorization header.

Note: For recommended ways to authenticate, see API authentication.

- - :param body: (required) - :type body: V1GetAuthTokenRequest - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._authentication_service_get_auth_token_serialize( - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetAuthTokenResponse", - '400': "object", - '401': "object", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def authentication_service_get_auth_token_without_preload_content( - self, - body: V1GetAuthTokenRequest, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Get Bearer Token - -

Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the Authorization header.

Note: For recommended ways to authenticate, see API authentication.

- - :param body: (required) - :type body: V1GetAuthTokenRequest - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._authentication_service_get_auth_token_serialize( - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetAuthTokenResponse", - '400': "object", - '401': "object", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _authentication_service_get_auth_token_serialize( - self, - 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]] = {} - _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 body is not None: - _body_params = body - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/auth/sa/oauth/token', - 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/skyflow/generated/rest/api/bin_lookup_api.py b/skyflow/generated/rest/api/bin_lookup_api.py deleted file mode 100644 index 1bb3e64b..00000000 --- a/skyflow/generated/rest/api/bin_lookup_api.py +++ /dev/null @@ -1,315 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from pydantic import Field -from typing_extensions import Annotated -from skyflow.generated.rest.models.v1_bin_list_request import V1BINListRequest -from skyflow.generated.rest.models.v1_bin_list_response import V1BINListResponse - -from skyflow.generated.rest.api_client import ApiClient, RequestSerialized -from skyflow.generated.rest.api_response import ApiResponse -from skyflow.generated.rest.rest import RESTResponseType - - -class BINLookupApi: - """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 - def b_in_list_service_list_cards_of_bin( - self, - body: Annotated[V1BINListRequest, Field(description="Request to return specific card metadata.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1BINListResponse: - """Get BIN - - Note: This endpoint is in beta and subject to change.

Returns the specified card metadata. - - :param body: Request to return specific card metadata. (required) - :type body: V1BINListRequest - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._b_in_list_service_list_cards_of_bin_serialize( - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BINListResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def b_in_list_service_list_cards_of_bin_with_http_info( - self, - body: Annotated[V1BINListRequest, Field(description="Request to return specific card metadata.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1BINListResponse]: - """Get BIN - - Note: This endpoint is in beta and subject to change.

Returns the specified card metadata. - - :param body: Request to return specific card metadata. (required) - :type body: V1BINListRequest - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._b_in_list_service_list_cards_of_bin_serialize( - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BINListResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def b_in_list_service_list_cards_of_bin_without_preload_content( - self, - body: Annotated[V1BINListRequest, Field(description="Request to return specific card metadata.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Get BIN - - Note: This endpoint is in beta and subject to change.

Returns the specified card metadata. - - :param body: Request to return specific card metadata. (required) - :type body: V1BINListRequest - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._b_in_list_service_list_cards_of_bin_serialize( - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BINListResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _b_in_list_service_list_cards_of_bin_serialize( - self, - 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]] = {} - _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 body is not None: - _body_params = body - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/card_lookup', - 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/skyflow/generated/rest/api/query_api.py b/skyflow/generated/rest/api/query_api.py deleted file mode 100644 index edf04f27..00000000 --- a/skyflow/generated/rest/api/query_api.py +++ /dev/null @@ -1,330 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from pydantic import Field, StrictStr -from typing_extensions import Annotated -from skyflow.generated.rest.models.query_service_execute_query_body import QueryServiceExecuteQueryBody -from skyflow.generated.rest.models.v1_get_query_response import V1GetQueryResponse - -from skyflow.generated.rest.api_client import ApiClient, RequestSerialized -from skyflow.generated.rest.api_response import ApiResponse -from skyflow.generated.rest.rest import RESTResponseType - - -class QueryApi: - """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 - def query_service_execute_query( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - body: QueryServiceExecuteQueryBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1GetQueryResponse: - """Execute Query - - Returns records for a valid SQL query. This endpoint
  • Can return redacted record values.
  • Supports only the SELECT command.
  • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
  • Can't modify the vault or perform transactions.
  • Can't return tokens.
  • Can't return file download or render URLs.
  • Doesn't support the WHERE keyword with columns using transient tokenization.
  • Doesn't support `?` conditional for columns with column-level encryption disabled.
    • - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param body: (required) - :type body: QueryServiceExecuteQueryBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._query_service_execute_query_serialize( - vault_id=vault_id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetQueryResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def query_service_execute_query_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - body: QueryServiceExecuteQueryBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1GetQueryResponse]: - """Execute Query - - Returns records for a valid SQL query. This endpoint
      • Can return redacted record values.
      • Supports only the SELECT command.
      • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
      • Can't modify the vault or perform transactions.
      • Can't return tokens.
      • Can't return file download or render URLs.
      • Doesn't support the WHERE keyword with columns using transient tokenization.
      • Doesn't support `?` conditional for columns with column-level encryption disabled.
        • - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param body: (required) - :type body: QueryServiceExecuteQueryBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._query_service_execute_query_serialize( - vault_id=vault_id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetQueryResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def query_service_execute_query_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - body: QueryServiceExecuteQueryBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Execute Query - - Returns records for a valid SQL query. This endpoint
          • Can return redacted record values.
          • Supports only the SELECT command.
          • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
          • Can't modify the vault or perform transactions.
          • Can't return tokens.
          • Can't return file download or render URLs.
          • Doesn't support the WHERE keyword with columns using transient tokenization.
          • Doesn't support `?` conditional for columns with column-level encryption disabled.
            • - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param body: (required) - :type body: QueryServiceExecuteQueryBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._query_service_execute_query_serialize( - vault_id=vault_id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetQueryResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _query_service_execute_query_serialize( - self, - vault_id, - 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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - if body is not None: - _body_params = body - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/vaults/{vaultID}/query', - 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/skyflow/generated/rest/api/records_api.py b/skyflow/generated/rest/api/records_api.py deleted file mode 100644 index ae9a2c29..00000000 --- a/skyflow/generated/rest/api/records_api.py +++ /dev/null @@ -1,3310 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
              • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
              • Production: https://*identifier*.vault.skyflowapis.com
              When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from pydantic import Field, StrictBool, StrictBytes, StrictStr, field_validator -from typing import List, Optional, Union -from typing_extensions import Annotated -from skyflow.generated.rest.models.record_service_batch_operation_body import RecordServiceBatchOperationBody -from skyflow.generated.rest.models.record_service_bulk_delete_record_body import RecordServiceBulkDeleteRecordBody -from skyflow.generated.rest.models.record_service_insert_record_body import RecordServiceInsertRecordBody -from skyflow.generated.rest.models.record_service_update_record_body import RecordServiceUpdateRecordBody -from skyflow.generated.rest.models.v1_batch_operation_response import V1BatchOperationResponse -from skyflow.generated.rest.models.v1_bulk_delete_record_response import V1BulkDeleteRecordResponse -from skyflow.generated.rest.models.v1_bulk_get_record_response import V1BulkGetRecordResponse -from skyflow.generated.rest.models.v1_delete_file_response import V1DeleteFileResponse -from skyflow.generated.rest.models.v1_delete_record_response import V1DeleteRecordResponse -from skyflow.generated.rest.models.v1_field_records import V1FieldRecords -from skyflow.generated.rest.models.v1_get_file_scan_status_response import V1GetFileScanStatusResponse -from skyflow.generated.rest.models.v1_insert_record_response import V1InsertRecordResponse -from skyflow.generated.rest.models.v1_update_record_response import V1UpdateRecordResponse - -from skyflow.generated.rest.api_client import ApiClient, RequestSerialized -from skyflow.generated.rest.api_response import ApiResponse -from skyflow.generated.rest.rest import RESTResponseType - - -class RecordsApi: - """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 - def file_service_delete_file( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - table_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - column_name: Annotated[StrictStr, Field(description="Name of the column that contains the file.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1DeleteFileResponse: - """Delete File - - Deletes a file from the specified record. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param table_name: Name of the table. (required) - :type table_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param column_name: Name of the column that contains the file. (required) - :type column_name: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_delete_file_serialize( - vault_id=vault_id, - table_name=table_name, - id=id, - column_name=column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DeleteFileResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def file_service_delete_file_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - table_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - column_name: Annotated[StrictStr, Field(description="Name of the column that contains the file.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1DeleteFileResponse]: - """Delete File - - Deletes a file from the specified record. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param table_name: Name of the table. (required) - :type table_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param column_name: Name of the column that contains the file. (required) - :type column_name: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_delete_file_serialize( - vault_id=vault_id, - table_name=table_name, - id=id, - column_name=column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DeleteFileResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def file_service_delete_file_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - table_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - column_name: Annotated[StrictStr, Field(description="Name of the column that contains the file.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Delete File - - Deletes a file from the specified record. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param table_name: Name of the table. (required) - :type table_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param column_name: Name of the column that contains the file. (required) - :type column_name: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_delete_file_serialize( - vault_id=vault_id, - table_name=table_name, - id=id, - column_name=column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DeleteFileResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _file_service_delete_file_serialize( - self, - vault_id, - table_name, - id, - column_name, - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if table_name is not None: - _path_params['tableName'] = table_name - if id is not None: - _path_params['ID'] = id - if column_name is not None: - _path_params['columnName'] = column_name - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='DELETE', - resource_path='/v1/vaults/{vaultID}/{tableName}/{ID}/files/{columnName}', - 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 - def file_service_get_file_scan_status( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - table_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - column_name: Annotated[StrictStr, Field(description="Name of the column that contains the file.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1GetFileScanStatusResponse: - """Get File Scan Status - - Returns the anti-virus scan status of a file. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param table_name: Name of the table. (required) - :type table_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param column_name: Name of the column that contains the file. (required) - :type column_name: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_get_file_scan_status_serialize( - vault_id=vault_id, - table_name=table_name, - id=id, - column_name=column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetFileScanStatusResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def file_service_get_file_scan_status_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - table_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - column_name: Annotated[StrictStr, Field(description="Name of the column that contains the file.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1GetFileScanStatusResponse]: - """Get File Scan Status - - Returns the anti-virus scan status of a file. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param table_name: Name of the table. (required) - :type table_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param column_name: Name of the column that contains the file. (required) - :type column_name: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_get_file_scan_status_serialize( - vault_id=vault_id, - table_name=table_name, - id=id, - column_name=column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetFileScanStatusResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def file_service_get_file_scan_status_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - table_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - column_name: Annotated[StrictStr, Field(description="Name of the column that contains the file.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Get File Scan Status - - Returns the anti-virus scan status of a file. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param table_name: Name of the table. (required) - :type table_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param column_name: Name of the column that contains the file. (required) - :type column_name: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_get_file_scan_status_serialize( - vault_id=vault_id, - table_name=table_name, - id=id, - column_name=column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1GetFileScanStatusResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _file_service_get_file_scan_status_serialize( - self, - vault_id, - table_name, - id, - column_name, - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if table_name is not None: - _path_params['tableName'] = table_name - if id is not None: - _path_params['ID'] = id - if column_name is not None: - _path_params['columnName'] = column_name - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/v1/vaults/{vaultID}/{tableName}/{ID}/files/{columnName}/scan-status', - 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 - def file_service_upload_file( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - file_column_name: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="Name of the column to store the file in. The column must have a file data type.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1UpdateRecordResponse: - """Upload File - - Uploads a file to the specified record. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param file_column_name: Name of the column to store the file in. The column must have a file data type. - :type file_column_name: bytearray - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_upload_file_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - file_column_name=file_column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1UpdateRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def file_service_upload_file_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - file_column_name: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="Name of the column to store the file in. The column must have a file data type.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1UpdateRecordResponse]: - """Upload File - - Uploads a file to the specified record. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param file_column_name: Name of the column to store the file in. The column must have a file data type. - :type file_column_name: bytearray - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_upload_file_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - file_column_name=file_column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1UpdateRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def file_service_upload_file_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - file_column_name: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="Name of the column to store the file in. The column must have a file data type.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Upload File - - Uploads a file to the specified record. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param file_column_name: Name of the column to store the file in. The column must have a file data type. - :type file_column_name: bytearray - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._file_service_upload_file_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - file_column_name=file_column_name, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1UpdateRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _file_service_upload_file_serialize( - self, - vault_id, - object_name, - id, - file_column_name, - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if object_name is not None: - _path_params['objectName'] = object_name - if id is not None: - _path_params['ID'] = id - # process the query parameters - # process the header parameters - # process the form parameters - if file_column_name is not None: - _files['fileColumnName'] = file_column_name - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - if _content_type: - _header_params['Content-Type'] = _content_type - else: - _default_content_type = ( - self.api_client.select_header_content_type( - [ - 'multipart/form-data' - ] - ) - ) - if _default_content_type is not None: - _header_params['Content-Type'] = _default_content_type - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/vaults/{vaultID}/{objectName}/{ID}/files', - 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 - def record_service_batch_operation( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - body: RecordServiceBatchOperationBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1BatchOperationResponse: - """Batch Operation - - Performs multiple record operations in a single transaction. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param body: (required) - :type body: RecordServiceBatchOperationBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_batch_operation_serialize( - vault_id=vault_id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BatchOperationResponse", - '207': "V1BatchOperationResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_batch_operation_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - body: RecordServiceBatchOperationBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1BatchOperationResponse]: - """Batch Operation - - Performs multiple record operations in a single transaction. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param body: (required) - :type body: RecordServiceBatchOperationBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_batch_operation_serialize( - vault_id=vault_id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BatchOperationResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_batch_operation_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - body: RecordServiceBatchOperationBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Batch Operation - - Performs multiple record operations in a single transaction. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param body: (required) - :type body: RecordServiceBatchOperationBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_batch_operation_serialize( - vault_id=vault_id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BatchOperationResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_batch_operation_serialize( - self, - vault_id, - 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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - if body is not None: - _body_params = body - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/vaults/{vaultID}', - 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 - def record_service_bulk_delete_record( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - body: RecordServiceBulkDeleteRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1BulkDeleteRecordResponse: - """Bulk Delete Records - - Deletes the specified records from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param body: (required) - :type body: RecordServiceBulkDeleteRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_bulk_delete_record_serialize( - vault_id=vault_id, - object_name=object_name, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BulkDeleteRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_bulk_delete_record_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - body: RecordServiceBulkDeleteRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1BulkDeleteRecordResponse]: - """Bulk Delete Records - - Deletes the specified records from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param body: (required) - :type body: RecordServiceBulkDeleteRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_bulk_delete_record_serialize( - vault_id=vault_id, - object_name=object_name, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BulkDeleteRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_bulk_delete_record_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - body: RecordServiceBulkDeleteRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Bulk Delete Records - - Deletes the specified records from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param body: (required) - :type body: RecordServiceBulkDeleteRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_bulk_delete_record_serialize( - vault_id=vault_id, - object_name=object_name, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BulkDeleteRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_bulk_delete_record_serialize( - self, - vault_id, - object_name, - 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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if object_name is not None: - _path_params['objectName'] = object_name - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - if body is not None: - _body_params = body - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='DELETE', - resource_path='/v1/vaults/{vaultID}/{objectName}', - 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 - def record_service_bulk_get_record( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table that contains the records.")], - skyflow_ids: Annotated[Optional[List[StrictStr]], Field(description="`skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

If not specified, returns the first 25 records in the table.")] = None, - redaction: Annotated[Optional[StrictStr], Field(description="Redaction level to enforce for the returned records. Subject to policies assigned to the API caller.")] = None, - tokenization: Annotated[Optional[StrictBool], Field(description="If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified.")] = None, - fields: Annotated[Optional[List[StrictStr]], Field(description="Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields.")] = None, - offset: Annotated[Optional[StrictStr], Field(description="Record position at which to start receiving data.")] = None, - limit: Annotated[Optional[StrictStr], Field(description="Number of record to return. Maximum 25.")] = None, - download_url: Annotated[Optional[StrictBool], Field(description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.")] = None, - column_name: Annotated[Optional[StrictStr], Field(description="Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error.")] = None, - column_values: Annotated[Optional[List[StrictStr]], Field(description="Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error.")] = None, - order_by: Annotated[Optional[StrictStr], Field(description="Order to return records, based on `skyflow_id` values. To disable, set to `NONE`.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1BulkGetRecordResponse: - """Get Record(s) - - Gets the specified records from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table that contains the records. (required) - :type object_name: str - :param skyflow_ids: `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

If not specified, returns the first 25 records in the table. - :type skyflow_ids: List[str] - :param redaction: Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. - :type redaction: str - :param tokenization: If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. - :type tokenization: bool - :param fields: Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields. - :type fields: List[str] - :param offset: Record position at which to start receiving data. - :type offset: str - :param limit: Number of record to return. Maximum 25. - :type limit: str - :param download_url: If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - :type download_url: bool - :param column_name: Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. - :type column_name: str - :param column_values: Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. - :type column_values: List[str] - :param order_by: Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. - :type order_by: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_bulk_get_record_serialize( - vault_id=vault_id, - object_name=object_name, - skyflow_ids=skyflow_ids, - redaction=redaction, - tokenization=tokenization, - fields=fields, - offset=offset, - limit=limit, - download_url=download_url, - column_name=column_name, - column_values=column_values, - order_by=order_by, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BulkGetRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_bulk_get_record_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table that contains the records.")], - skyflow_ids: Annotated[Optional[List[StrictStr]], Field(description="`skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

If not specified, returns the first 25 records in the table.")] = None, - redaction: Annotated[Optional[StrictStr], Field(description="Redaction level to enforce for the returned records. Subject to policies assigned to the API caller.")] = None, - tokenization: Annotated[Optional[StrictBool], Field(description="If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified.")] = None, - fields: Annotated[Optional[List[StrictStr]], Field(description="Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields.")] = None, - offset: Annotated[Optional[StrictStr], Field(description="Record position at which to start receiving data.")] = None, - limit: Annotated[Optional[StrictStr], Field(description="Number of record to return. Maximum 25.")] = None, - download_url: Annotated[Optional[StrictBool], Field(description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.")] = None, - column_name: Annotated[Optional[StrictStr], Field(description="Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error.")] = None, - column_values: Annotated[Optional[List[StrictStr]], Field(description="Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error.")] = None, - order_by: Annotated[Optional[StrictStr], Field(description="Order to return records, based on `skyflow_id` values. To disable, set to `NONE`.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1BulkGetRecordResponse]: - """Get Record(s) - - Gets the specified records from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table that contains the records. (required) - :type object_name: str - :param skyflow_ids: `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

If not specified, returns the first 25 records in the table. - :type skyflow_ids: List[str] - :param redaction: Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. - :type redaction: str - :param tokenization: If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. - :type tokenization: bool - :param fields: Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields. - :type fields: List[str] - :param offset: Record position at which to start receiving data. - :type offset: str - :param limit: Number of record to return. Maximum 25. - :type limit: str - :param download_url: If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - :type download_url: bool - :param column_name: Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. - :type column_name: str - :param column_values: Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. - :type column_values: List[str] - :param order_by: Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. - :type order_by: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_bulk_get_record_serialize( - vault_id=vault_id, - object_name=object_name, - skyflow_ids=skyflow_ids, - redaction=redaction, - tokenization=tokenization, - fields=fields, - offset=offset, - limit=limit, - download_url=download_url, - column_name=column_name, - column_values=column_values, - order_by=order_by, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BulkGetRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_bulk_get_record_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table that contains the records.")], - skyflow_ids: Annotated[Optional[List[StrictStr]], Field(description="`skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

If not specified, returns the first 25 records in the table.")] = None, - redaction: Annotated[Optional[StrictStr], Field(description="Redaction level to enforce for the returned records. Subject to policies assigned to the API caller.")] = None, - tokenization: Annotated[Optional[StrictBool], Field(description="If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified.")] = None, - fields: Annotated[Optional[List[StrictStr]], Field(description="Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields.")] = None, - offset: Annotated[Optional[StrictStr], Field(description="Record position at which to start receiving data.")] = None, - limit: Annotated[Optional[StrictStr], Field(description="Number of record to return. Maximum 25.")] = None, - download_url: Annotated[Optional[StrictBool], Field(description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.")] = None, - column_name: Annotated[Optional[StrictStr], Field(description="Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error.")] = None, - column_values: Annotated[Optional[List[StrictStr]], Field(description="Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error.")] = None, - order_by: Annotated[Optional[StrictStr], Field(description="Order to return records, based on `skyflow_id` values. To disable, set to `NONE`.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Get Record(s) - - Gets the specified records from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table that contains the records. (required) - :type object_name: str - :param skyflow_ids: `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

If not specified, returns the first 25 records in the table. - :type skyflow_ids: List[str] - :param redaction: Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. - :type redaction: str - :param tokenization: If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. - :type tokenization: bool - :param fields: Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields. - :type fields: List[str] - :param offset: Record position at which to start receiving data. - :type offset: str - :param limit: Number of record to return. Maximum 25. - :type limit: str - :param download_url: If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - :type download_url: bool - :param column_name: Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. - :type column_name: str - :param column_values: Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. - :type column_values: List[str] - :param order_by: Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. - :type order_by: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_bulk_get_record_serialize( - vault_id=vault_id, - object_name=object_name, - skyflow_ids=skyflow_ids, - redaction=redaction, - tokenization=tokenization, - fields=fields, - offset=offset, - limit=limit, - download_url=download_url, - column_name=column_name, - column_values=column_values, - order_by=order_by, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1BulkGetRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_bulk_get_record_serialize( - self, - vault_id, - object_name, - skyflow_ids, - redaction, - tokenization, - fields, - offset, - limit, - download_url, - column_name, - column_values, - order_by, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - 'skyflow_ids': 'multi', - 'fields': 'multi', - 'column_values': 'multi', - } - - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if object_name is not None: - _path_params['objectName'] = object_name - # process the query parameters - if skyflow_ids is not None: - - _query_params.append(('skyflow_ids', skyflow_ids)) - - if redaction is not None: - - _query_params.append(('redaction', redaction)) - - if tokenization is not None: - - _query_params.append(('tokenization', tokenization)) - - if fields is not None: - - _query_params.append(('fields', fields)) - - if offset is not None: - - _query_params.append(('offset', offset)) - - if limit is not None: - - _query_params.append(('limit', limit)) - - if download_url is not None: - - _query_params.append(('downloadURL', download_url)) - - if column_name is not None: - - _query_params.append(('column_name', column_name)) - - if column_values is not None: - - _query_params.append(('column_values', column_values)) - - if order_by is not None: - - _query_params.append(('order_by', order_by)) - - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/v1/vaults/{vaultID}/{objectName}', - 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 - def record_service_delete_record( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record to delete.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1DeleteRecordResponse: - """Delete Record - - Deletes the specified record from a table.

Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record to delete. (required) - :type id: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_delete_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DeleteRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_delete_record_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record to delete.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1DeleteRecordResponse]: - """Delete Record - - Deletes the specified record from a table.

Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record to delete. (required) - :type id: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_delete_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DeleteRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_delete_record_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record to delete.")], - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Delete Record - - Deletes the specified record from a table.

Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record to delete. (required) - :type id: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_delete_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DeleteRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_delete_record_serialize( - self, - vault_id, - object_name, - 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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if object_name is not None: - _path_params['objectName'] = object_name - if id is not None: - _path_params['ID'] = id - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='DELETE', - resource_path='/v1/vaults/{vaultID}/{objectName}/{ID}', - 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 - def record_service_get_record( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - redaction: Annotated[Optional[StrictStr], Field(description="Redaction level to enforce for the returned record. Subject to policies assigned to the API caller.")] = None, - tokenization: Annotated[Optional[StrictBool], Field(description="If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified.")] = None, - fields: Annotated[Optional[List[StrictStr]], Field(description="Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields.")] = None, - download_url: Annotated[Optional[StrictBool], Field(description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1FieldRecords: - """Get Record By ID - - Returns the specified record from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param redaction: Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. - :type redaction: str - :param tokenization: If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. - :type tokenization: bool - :param fields: Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields. - :type fields: List[str] - :param download_url: If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - :type download_url: bool - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_get_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - redaction=redaction, - tokenization=tokenization, - fields=fields, - download_url=download_url, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1FieldRecords", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_get_record_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - redaction: Annotated[Optional[StrictStr], Field(description="Redaction level to enforce for the returned record. Subject to policies assigned to the API caller.")] = None, - tokenization: Annotated[Optional[StrictBool], Field(description="If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified.")] = None, - fields: Annotated[Optional[List[StrictStr]], Field(description="Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields.")] = None, - download_url: Annotated[Optional[StrictBool], Field(description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1FieldRecords]: - """Get Record By ID - - Returns the specified record from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param redaction: Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. - :type redaction: str - :param tokenization: If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. - :type tokenization: bool - :param fields: Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields. - :type fields: List[str] - :param download_url: If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - :type download_url: bool - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_get_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - redaction=redaction, - tokenization=tokenization, - fields=fields, - download_url=download_url, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1FieldRecords", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_get_record_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - redaction: Annotated[Optional[StrictStr], Field(description="Redaction level to enforce for the returned record. Subject to policies assigned to the API caller.")] = None, - tokenization: Annotated[Optional[StrictBool], Field(description="If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified.")] = None, - fields: Annotated[Optional[List[StrictStr]], Field(description="Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields.")] = None, - download_url: Annotated[Optional[StrictBool], Field(description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Get Record By ID - - Returns the specified record from a table. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param redaction: Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. - :type redaction: str - :param tokenization: If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. - :type tokenization: bool - :param fields: Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

If not specified, returns all fields. - :type fields: List[str] - :param download_url: If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - :type download_url: bool - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_get_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - redaction=redaction, - tokenization=tokenization, - fields=fields, - download_url=download_url, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1FieldRecords", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_get_record_serialize( - self, - vault_id, - object_name, - id, - redaction, - tokenization, - fields, - download_url, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - 'fields': 'multi', - } - - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if object_name is not None: - _path_params['objectName'] = object_name - if id is not None: - _path_params['ID'] = id - # process the query parameters - if redaction is not None: - - _query_params.append(('redaction', redaction)) - - if tokenization is not None: - - _query_params.append(('tokenization', tokenization)) - - if fields is not None: - - _query_params.append(('fields', fields)) - - if download_url is not None: - - _query_params.append(('downloadURL', download_url)) - - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/v1/vaults/{vaultID}/{objectName}/{ID}', - 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 - def record_service_insert_record( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - body: RecordServiceInsertRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1InsertRecordResponse: - """Insert Records - - Inserts a record in the specified table.

The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.

Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param body: (required) - :type body: RecordServiceInsertRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_insert_record_serialize( - vault_id=vault_id, - object_name=object_name, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1InsertRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_insert_record_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - body: RecordServiceInsertRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1InsertRecordResponse]: - """Insert Records - - Inserts a record in the specified table.

The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.

Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param body: (required) - :type body: RecordServiceInsertRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_insert_record_serialize( - vault_id=vault_id, - object_name=object_name, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1InsertRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_insert_record_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - body: RecordServiceInsertRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Insert Records - - Inserts a record in the specified table.

The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.

Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param body: (required) - :type body: RecordServiceInsertRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_insert_record_serialize( - vault_id=vault_id, - object_name=object_name, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1InsertRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_insert_record_serialize( - self, - vault_id, - object_name, - 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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if object_name is not None: - _path_params['objectName'] = object_name - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - if body is not None: - _body_params = body - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/vaults/{vaultID}/{objectName}', - 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 - def record_service_update_record( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - body: RecordServiceUpdateRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1UpdateRecordResponse: - """Update Record - - Updates the specified record in a table.

When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

The time-to-live (TTL) for a transient field resets when the field value is updated. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param body: (required) - :type body: RecordServiceUpdateRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_update_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1UpdateRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_update_record_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - body: RecordServiceUpdateRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1UpdateRecordResponse]: - """Update Record - - Updates the specified record in a table.

When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

The time-to-live (TTL) for a transient field resets when the field value is updated. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param body: (required) - :type body: RecordServiceUpdateRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_update_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1UpdateRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_update_record_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - object_name: Annotated[StrictStr, Field(description="Name of the table.")], - id: Annotated[StrictStr, Field(description="`skyflow_id` of the record.")], - body: RecordServiceUpdateRecordBody, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Update Record - - Updates the specified record in a table.

When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

The time-to-live (TTL) for a transient field resets when the field value is updated. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param object_name: Name of the table. (required) - :type object_name: str - :param id: `skyflow_id` of the record. (required) - :type id: str - :param body: (required) - :type body: RecordServiceUpdateRecordBody - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_update_record_serialize( - vault_id=vault_id, - object_name=object_name, - id=id, - body=body, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1UpdateRecordResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_update_record_serialize( - self, - vault_id, - object_name, - id, - 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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - if object_name is not None: - _path_params['objectName'] = object_name - if id is not None: - _path_params['ID'] = id - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - if body is not None: - _body_params = body - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='PUT', - resource_path='/v1/vaults/{vaultID}/{objectName}/{ID}', - 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/skyflow/generated/rest/api/tokens_api.py b/skyflow/generated/rest/api/tokens_api.py deleted file mode 100644 index e21e7935..00000000 --- a/skyflow/generated/rest/api/tokens_api.py +++ /dev/null @@ -1,623 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from pydantic import Field, StrictStr -from typing_extensions import Annotated -from skyflow.generated.rest.models.v1_detokenize_payload import V1DetokenizePayload -from skyflow.generated.rest.models.v1_detokenize_response import V1DetokenizeResponse -from skyflow.generated.rest.models.v1_tokenize_payload import V1TokenizePayload -from skyflow.generated.rest.models.v1_tokenize_response import V1TokenizeResponse - -from skyflow.generated.rest.api_client import ApiClient, RequestSerialized -from skyflow.generated.rest.api_response import ApiResponse -from skyflow.generated.rest.rest import RESTResponseType - - -class TokensApi: - """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 - def record_service_detokenize( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - detokenize_payload: V1DetokenizePayload, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1DetokenizeResponse: - """Detokenize - - Returns records that correspond to the specified tokens. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param detokenize_payload: (required) - :type detokenize_payload: V1DetokenizePayload - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_detokenize_serialize( - vault_id=vault_id, - detokenize_payload=detokenize_payload, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DetokenizeResponse", - '207': "V1DetokenizeResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_detokenize_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - detokenize_payload: V1DetokenizePayload, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1DetokenizeResponse]: - """Detokenize - - Returns records that correspond to the specified tokens. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param detokenize_payload: (required) - :type detokenize_payload: V1DetokenizePayload - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_detokenize_serialize( - vault_id=vault_id, - detokenize_payload=detokenize_payload, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DetokenizeResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_detokenize_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - detokenize_payload: V1DetokenizePayload, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Detokenize - - Returns records that correspond to the specified tokens. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param detokenize_payload: (required) - :type detokenize_payload: V1DetokenizePayload - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_detokenize_serialize( - vault_id=vault_id, - detokenize_payload=detokenize_payload, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1DetokenizeResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_detokenize_serialize( - self, - vault_id, - detokenize_payload, - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - if detokenize_payload is not None: - _body_params = detokenize_payload - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/vaults/{vaultID}/detokenize', - 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 - def record_service_tokenize( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - tokenize_payload: V1TokenizePayload, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> V1TokenizeResponse: - """Tokenize - - Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.

Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see Insert Record and the tokenization parameter. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param tokenize_payload: (required) - :type tokenize_payload: V1TokenizePayload - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_tokenize_serialize( - vault_id=vault_id, - tokenize_payload=tokenize_payload, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1TokenizeResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - def record_service_tokenize_with_http_info( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - tokenize_payload: V1TokenizePayload, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[V1TokenizeResponse]: - """Tokenize - - Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.

Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see Insert Record and the tokenization parameter. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param tokenize_payload: (required) - :type tokenize_payload: V1TokenizePayload - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_tokenize_serialize( - vault_id=vault_id, - tokenize_payload=tokenize_payload, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1TokenizeResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - def record_service_tokenize_without_preload_content( - self, - vault_id: Annotated[StrictStr, Field(description="ID of the vault.")], - tokenize_payload: V1TokenizePayload, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """Tokenize - - Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.

Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see Insert Record and the tokenization parameter. - - :param vault_id: ID of the vault. (required) - :type vault_id: str - :param tokenize_payload: (required) - :type tokenize_payload: V1TokenizePayload - :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. - :type _request_timeout: int, tuple(int, int), optional - :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. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._record_service_tokenize_serialize( - vault_id=vault_id, - tokenize_payload=tokenize_payload, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "V1TokenizeResponse", - '404': "object", - } - response_data = self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _record_service_tokenize_serialize( - self, - vault_id, - tokenize_payload, - _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]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - if vault_id is not None: - _path_params['vaultID'] = vault_id - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - if tokenize_payload is not None: - _body_params = tokenize_payload - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - # set the HTTP header `Content-Type` - 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 - - # authentication setting - _auth_settings: List[str] = [ - 'Bearer' - ] - - return self.api_client.param_serialize( - method='POST', - resource_path='/v1/vaults/{vaultID}/tokenize', - 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/skyflow/generated/rest/api_client.py b/skyflow/generated/rest/api_client.py deleted file mode 100644 index 8aa5e6a9..00000000 --- a/skyflow/generated/rest/api_client.py +++ /dev/null @@ -1,789 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 skyflow.generated.rest.configuration import Configuration -from skyflow.generated.rest.api_response import ApiResponse, T as ApiResponseT -import skyflow.generated.rest.models -from skyflow.generated.rest import rest -from skyflow.generated.rest.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 - ) -> 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 content_type.startswith("application/json"): - if response_text == "": - data = "" - else: - data = json.loads(response_text) - elif content_type.startswith("text/plain"): - 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(skyflow.generated.rest.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]]): - """Builds form parameters. - - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - for k, v in files.items(): - 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 - else: - raise ValueError("Unsupported file value") - mimetype = ( - 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/skyflow/generated/rest/api_response.py b/skyflow/generated/rest/api_response.py deleted file mode 100644 index 9bc7c11f..00000000 --- a/skyflow/generated/rest/api_response.py +++ /dev/null @@ -1,21 +0,0 @@ -"""API response object.""" - -from __future__ import annotations -from typing import Optional, Generic, Mapping, TypeVar -from pydantic import Field, StrictInt, StrictBytes, BaseModel - -T = TypeVar("T") - -class ApiResponse(BaseModel, Generic[T]): - """ - API response object - """ - - status_code: StrictInt = 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: StrictBytes = Field(description="Raw data (HTTP response body)") - - model_config = { - "arbitrary_types_allowed": True - } diff --git a/skyflow/generated/rest/audit/__init__.py b/skyflow/generated/rest/audit/__init__.py new file mode 100644 index 00000000..38fe28d3 --- /dev/null +++ b/skyflow/generated/rest/audit/__init__.py @@ -0,0 +1,19 @@ +# This file was auto-generated by Fern from our API Definition. + +from .types import ( + AuditServiceListAuditEventsRequestFilterOpsActionType, + AuditServiceListAuditEventsRequestFilterOpsContextAccessType, + AuditServiceListAuditEventsRequestFilterOpsContextActorType, + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode, + AuditServiceListAuditEventsRequestFilterOpsResourceType, + AuditServiceListAuditEventsRequestSortOpsOrderBy, +) + +__all__ = [ + "AuditServiceListAuditEventsRequestFilterOpsActionType", + "AuditServiceListAuditEventsRequestFilterOpsContextAccessType", + "AuditServiceListAuditEventsRequestFilterOpsContextActorType", + "AuditServiceListAuditEventsRequestFilterOpsContextAuthMode", + "AuditServiceListAuditEventsRequestFilterOpsResourceType", + "AuditServiceListAuditEventsRequestSortOpsOrderBy", +] diff --git a/skyflow/generated/rest/audit/client.py b/skyflow/generated/rest/audit/client.py new file mode 100644 index 00000000..3b4d329a --- /dev/null +++ b/skyflow/generated/rest/audit/client.py @@ -0,0 +1,509 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.client_wrapper import SyncClientWrapper +import typing +from .types.audit_service_list_audit_events_request_filter_ops_context_actor_type import ( + AuditServiceListAuditEventsRequestFilterOpsContextActorType, +) +from .types.audit_service_list_audit_events_request_filter_ops_context_access_type import ( + AuditServiceListAuditEventsRequestFilterOpsContextAccessType, +) +from .types.audit_service_list_audit_events_request_filter_ops_context_auth_mode import ( + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode, +) +from .types.audit_service_list_audit_events_request_filter_ops_action_type import ( + AuditServiceListAuditEventsRequestFilterOpsActionType, +) +from .types.audit_service_list_audit_events_request_filter_ops_resource_type import ( + AuditServiceListAuditEventsRequestFilterOpsResourceType, +) +from .types.audit_service_list_audit_events_request_sort_ops_order_by import ( + AuditServiceListAuditEventsRequestSortOpsOrderBy, +) +from ..core.request_options import RequestOptions +from ..types.v_1_audit_response import V1AuditResponse +from ..core.pydantic_utilities import parse_obj_as +from ..errors.not_found_error import NotFoundError +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper + + +class AuditClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def audit_service_list_audit_events( + self, + *, + filter_ops_account_id: str, + filter_ops_context_change_id: typing.Optional[str] = None, + filter_ops_context_request_id: typing.Optional[str] = None, + filter_ops_context_trace_id: typing.Optional[str] = None, + filter_ops_context_session_id: typing.Optional[str] = None, + filter_ops_context_actor: typing.Optional[str] = None, + filter_ops_context_actor_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextActorType + ] = None, + filter_ops_context_access_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAccessType + ] = None, + filter_ops_context_ip_address: typing.Optional[str] = None, + filter_ops_context_origin: typing.Optional[str] = None, + filter_ops_context_auth_mode: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode + ] = None, + filter_ops_context_jwt_id: typing.Optional[str] = None, + filter_ops_context_bearer_token_context_id: typing.Optional[str] = None, + filter_ops_parent_account_id: typing.Optional[str] = None, + filter_ops_workspace_id: typing.Optional[str] = None, + filter_ops_vault_id: typing.Optional[str] = None, + filter_ops_resource_i_ds: typing.Optional[str] = None, + filter_ops_action_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] = None, + filter_ops_resource_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] = None, + filter_ops_tags: typing.Optional[str] = None, + filter_ops_response_code: typing.Optional[int] = None, + filter_ops_start_time: typing.Optional[str] = None, + filter_ops_end_time: typing.Optional[str] = None, + filter_ops_api_name: typing.Optional[str] = None, + filter_ops_response_message: typing.Optional[str] = None, + filter_ops_http_method: typing.Optional[str] = None, + filter_ops_http_uri: typing.Optional[str] = None, + sort_ops_sort_by: typing.Optional[str] = None, + sort_ops_order_by: typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] = None, + after_ops_timestamp: typing.Optional[str] = None, + after_ops_change_id: typing.Optional[str] = None, + limit: typing.Optional[int] = None, + offset: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1AuditResponse: + """ + Lists audit events that match query parameters. + + Parameters + ---------- + filter_ops_account_id : str + Resources with the specified account ID. + + filter_ops_context_change_id : typing.Optional[str] + ID for the audit event. + + filter_ops_context_request_id : typing.Optional[str] + ID for the request that caused the event. + + filter_ops_context_trace_id : typing.Optional[str] + ID for the request set by the service that received the request. + + filter_ops_context_session_id : typing.Optional[str] + ID for the session in which the request was sent. + + filter_ops_context_actor : typing.Optional[str] + Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. + + filter_ops_context_actor_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextActorType] + Type of member who sent the request. + + filter_ops_context_access_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAccessType] + Type of access for the request. + + filter_ops_context_ip_address : typing.Optional[str] + IP Address of the client that made the request. + + filter_ops_context_origin : typing.Optional[str] + HTTP Origin request header (including scheme, hostname, and port) of the request. + + filter_ops_context_auth_mode : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAuthMode] + Authentication mode the `actor` used. + + filter_ops_context_jwt_id : typing.Optional[str] + ID of the JWT token. + + filter_ops_context_bearer_token_context_id : typing.Optional[str] + Embedded User Context. + + filter_ops_parent_account_id : typing.Optional[str] + Resources with the specified parent account ID. + + filter_ops_workspace_id : typing.Optional[str] + Resources with the specified workspace ID. + + filter_ops_vault_id : typing.Optional[str] + Resources with the specified vault ID. + + filter_ops_resource_i_ds : typing.Optional[str] + Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "\/\". For example, "VAULT/12345, USER/67890". + + filter_ops_action_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] + Events with the specified action type. + + filter_ops_resource_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] + Resources with the specified type. + + filter_ops_tags : typing.Optional[str] + Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get". + + filter_ops_response_code : typing.Optional[int] + HTTP response code of the request. + + filter_ops_start_time : typing.Optional[str] + Start timestamp for the query, in SQL format. + + filter_ops_end_time : typing.Optional[str] + End timestamp for the query, in SQL format. + + filter_ops_api_name : typing.Optional[str] + Name of the API called in the request. + + filter_ops_response_message : typing.Optional[str] + Response message of the request. + + filter_ops_http_method : typing.Optional[str] + HTTP method of the request. + + filter_ops_http_uri : typing.Optional[str] + HTTP URI of the request. + + sort_ops_sort_by : typing.Optional[str] + Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase"). + + sort_ops_order_by : typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] + Ascending or descending ordering of results. + + after_ops_timestamp : typing.Optional[str] + Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + after_ops_change_id : typing.Optional[str] + Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + limit : typing.Optional[int] + Number of results to return. + + offset : typing.Optional[int] + Record position at which to start returning results. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1AuditResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.audit.audit_service_list_audit_events( + filter_ops_account_id="filterOps.accountID", + ) + """ + _response = self._client_wrapper.httpx_client.request( + "v1/audit/events", + method="GET", + params={ + "filterOps.context.changeID": filter_ops_context_change_id, + "filterOps.context.requestID": filter_ops_context_request_id, + "filterOps.context.traceID": filter_ops_context_trace_id, + "filterOps.context.sessionID": filter_ops_context_session_id, + "filterOps.context.actor": filter_ops_context_actor, + "filterOps.context.actorType": filter_ops_context_actor_type, + "filterOps.context.accessType": filter_ops_context_access_type, + "filterOps.context.ipAddress": filter_ops_context_ip_address, + "filterOps.context.origin": filter_ops_context_origin, + "filterOps.context.authMode": filter_ops_context_auth_mode, + "filterOps.context.jwtID": filter_ops_context_jwt_id, + "filterOps.context.bearerTokenContextID": filter_ops_context_bearer_token_context_id, + "filterOps.parentAccountID": filter_ops_parent_account_id, + "filterOps.accountID": filter_ops_account_id, + "filterOps.workspaceID": filter_ops_workspace_id, + "filterOps.vaultID": filter_ops_vault_id, + "filterOps.resourceIDs": filter_ops_resource_i_ds, + "filterOps.actionType": filter_ops_action_type, + "filterOps.resourceType": filter_ops_resource_type, + "filterOps.tags": filter_ops_tags, + "filterOps.responseCode": filter_ops_response_code, + "filterOps.startTime": filter_ops_start_time, + "filterOps.endTime": filter_ops_end_time, + "filterOps.apiName": filter_ops_api_name, + "filterOps.responseMessage": filter_ops_response_message, + "filterOps.httpMethod": filter_ops_http_method, + "filterOps.httpURI": filter_ops_http_uri, + "sortOps.sortBy": sort_ops_sort_by, + "sortOps.orderBy": sort_ops_order_by, + "afterOps.timestamp": after_ops_timestamp, + "afterOps.changeID": after_ops_change_id, + "limit": limit, + "offset": offset, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1AuditResponse, + parse_obj_as( + type_=V1AuditResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + +class AsyncAuditClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def audit_service_list_audit_events( + self, + *, + filter_ops_account_id: str, + filter_ops_context_change_id: typing.Optional[str] = None, + filter_ops_context_request_id: typing.Optional[str] = None, + filter_ops_context_trace_id: typing.Optional[str] = None, + filter_ops_context_session_id: typing.Optional[str] = None, + filter_ops_context_actor: typing.Optional[str] = None, + filter_ops_context_actor_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextActorType + ] = None, + filter_ops_context_access_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAccessType + ] = None, + filter_ops_context_ip_address: typing.Optional[str] = None, + filter_ops_context_origin: typing.Optional[str] = None, + filter_ops_context_auth_mode: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode + ] = None, + filter_ops_context_jwt_id: typing.Optional[str] = None, + filter_ops_context_bearer_token_context_id: typing.Optional[str] = None, + filter_ops_parent_account_id: typing.Optional[str] = None, + filter_ops_workspace_id: typing.Optional[str] = None, + filter_ops_vault_id: typing.Optional[str] = None, + filter_ops_resource_i_ds: typing.Optional[str] = None, + filter_ops_action_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] = None, + filter_ops_resource_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] = None, + filter_ops_tags: typing.Optional[str] = None, + filter_ops_response_code: typing.Optional[int] = None, + filter_ops_start_time: typing.Optional[str] = None, + filter_ops_end_time: typing.Optional[str] = None, + filter_ops_api_name: typing.Optional[str] = None, + filter_ops_response_message: typing.Optional[str] = None, + filter_ops_http_method: typing.Optional[str] = None, + filter_ops_http_uri: typing.Optional[str] = None, + sort_ops_sort_by: typing.Optional[str] = None, + sort_ops_order_by: typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] = None, + after_ops_timestamp: typing.Optional[str] = None, + after_ops_change_id: typing.Optional[str] = None, + limit: typing.Optional[int] = None, + offset: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1AuditResponse: + """ + Lists audit events that match query parameters. + + Parameters + ---------- + filter_ops_account_id : str + Resources with the specified account ID. + + filter_ops_context_change_id : typing.Optional[str] + ID for the audit event. + + filter_ops_context_request_id : typing.Optional[str] + ID for the request that caused the event. + + filter_ops_context_trace_id : typing.Optional[str] + ID for the request set by the service that received the request. + + filter_ops_context_session_id : typing.Optional[str] + ID for the session in which the request was sent. + + filter_ops_context_actor : typing.Optional[str] + Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. + + filter_ops_context_actor_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextActorType] + Type of member who sent the request. + + filter_ops_context_access_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAccessType] + Type of access for the request. + + filter_ops_context_ip_address : typing.Optional[str] + IP Address of the client that made the request. + + filter_ops_context_origin : typing.Optional[str] + HTTP Origin request header (including scheme, hostname, and port) of the request. + + filter_ops_context_auth_mode : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAuthMode] + Authentication mode the `actor` used. + + filter_ops_context_jwt_id : typing.Optional[str] + ID of the JWT token. + + filter_ops_context_bearer_token_context_id : typing.Optional[str] + Embedded User Context. + + filter_ops_parent_account_id : typing.Optional[str] + Resources with the specified parent account ID. + + filter_ops_workspace_id : typing.Optional[str] + Resources with the specified workspace ID. + + filter_ops_vault_id : typing.Optional[str] + Resources with the specified vault ID. + + filter_ops_resource_i_ds : typing.Optional[str] + Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "\/\". For example, "VAULT/12345, USER/67890". + + filter_ops_action_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] + Events with the specified action type. + + filter_ops_resource_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] + Resources with the specified type. + + filter_ops_tags : typing.Optional[str] + Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get". + + filter_ops_response_code : typing.Optional[int] + HTTP response code of the request. + + filter_ops_start_time : typing.Optional[str] + Start timestamp for the query, in SQL format. + + filter_ops_end_time : typing.Optional[str] + End timestamp for the query, in SQL format. + + filter_ops_api_name : typing.Optional[str] + Name of the API called in the request. + + filter_ops_response_message : typing.Optional[str] + Response message of the request. + + filter_ops_http_method : typing.Optional[str] + HTTP method of the request. + + filter_ops_http_uri : typing.Optional[str] + HTTP URI of the request. + + sort_ops_sort_by : typing.Optional[str] + Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase"). + + sort_ops_order_by : typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] + Ascending or descending ordering of results. + + after_ops_timestamp : typing.Optional[str] + Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + after_ops_change_id : typing.Optional[str] + Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + limit : typing.Optional[int] + Number of results to return. + + offset : typing.Optional[int] + Record position at which to start returning results. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1AuditResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.audit.audit_service_list_audit_events( + filter_ops_account_id="filterOps.accountID", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + "v1/audit/events", + method="GET", + params={ + "filterOps.context.changeID": filter_ops_context_change_id, + "filterOps.context.requestID": filter_ops_context_request_id, + "filterOps.context.traceID": filter_ops_context_trace_id, + "filterOps.context.sessionID": filter_ops_context_session_id, + "filterOps.context.actor": filter_ops_context_actor, + "filterOps.context.actorType": filter_ops_context_actor_type, + "filterOps.context.accessType": filter_ops_context_access_type, + "filterOps.context.ipAddress": filter_ops_context_ip_address, + "filterOps.context.origin": filter_ops_context_origin, + "filterOps.context.authMode": filter_ops_context_auth_mode, + "filterOps.context.jwtID": filter_ops_context_jwt_id, + "filterOps.context.bearerTokenContextID": filter_ops_context_bearer_token_context_id, + "filterOps.parentAccountID": filter_ops_parent_account_id, + "filterOps.accountID": filter_ops_account_id, + "filterOps.workspaceID": filter_ops_workspace_id, + "filterOps.vaultID": filter_ops_vault_id, + "filterOps.resourceIDs": filter_ops_resource_i_ds, + "filterOps.actionType": filter_ops_action_type, + "filterOps.resourceType": filter_ops_resource_type, + "filterOps.tags": filter_ops_tags, + "filterOps.responseCode": filter_ops_response_code, + "filterOps.startTime": filter_ops_start_time, + "filterOps.endTime": filter_ops_end_time, + "filterOps.apiName": filter_ops_api_name, + "filterOps.responseMessage": filter_ops_response_message, + "filterOps.httpMethod": filter_ops_http_method, + "filterOps.httpURI": filter_ops_http_uri, + "sortOps.sortBy": sort_ops_sort_by, + "sortOps.orderBy": sort_ops_order_by, + "afterOps.timestamp": after_ops_timestamp, + "afterOps.changeID": after_ops_change_id, + "limit": limit, + "offset": offset, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1AuditResponse, + parse_obj_as( + type_=V1AuditResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/audit/types/__init__.py b/skyflow/generated/rest/audit/types/__init__.py new file mode 100644 index 00000000..39f38866 --- /dev/null +++ b/skyflow/generated/rest/audit/types/__init__.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +from .audit_service_list_audit_events_request_filter_ops_action_type import ( + AuditServiceListAuditEventsRequestFilterOpsActionType, +) +from .audit_service_list_audit_events_request_filter_ops_context_access_type import ( + AuditServiceListAuditEventsRequestFilterOpsContextAccessType, +) +from .audit_service_list_audit_events_request_filter_ops_context_actor_type import ( + AuditServiceListAuditEventsRequestFilterOpsContextActorType, +) +from .audit_service_list_audit_events_request_filter_ops_context_auth_mode import ( + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode, +) +from .audit_service_list_audit_events_request_filter_ops_resource_type import ( + AuditServiceListAuditEventsRequestFilterOpsResourceType, +) +from .audit_service_list_audit_events_request_sort_ops_order_by import AuditServiceListAuditEventsRequestSortOpsOrderBy + +__all__ = [ + "AuditServiceListAuditEventsRequestFilterOpsActionType", + "AuditServiceListAuditEventsRequestFilterOpsContextAccessType", + "AuditServiceListAuditEventsRequestFilterOpsContextActorType", + "AuditServiceListAuditEventsRequestFilterOpsContextAuthMode", + "AuditServiceListAuditEventsRequestFilterOpsResourceType", + "AuditServiceListAuditEventsRequestSortOpsOrderBy", +] diff --git a/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_action_type.py b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_action_type.py new file mode 100644 index 00000000..24df22e1 --- /dev/null +++ b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_action_type.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +AuditServiceListAuditEventsRequestFilterOpsActionType = typing.Union[ + typing.Literal[ + "NONE", + "ASSIGN", + "CREATE", + "DELETE", + "EXECUTE", + "LIST", + "READ", + "UNASSIGN", + "UPDATE", + "VALIDATE", + "LOGIN", + "ROTATE", + "SCHEDULEROTATION", + "SCHEDULEROTATIONALERT", + "IMPORT", + "GETIMPORTPARAMETERS", + "PING", + "GETCLOUDPROVIDER", + ], + typing.Any, +] diff --git a/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_access_type.py b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_access_type.py new file mode 100644 index 00000000..1349c539 --- /dev/null +++ b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_access_type.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +AuditServiceListAuditEventsRequestFilterOpsContextAccessType = typing.Union[ + typing.Literal["ACCESS_NONE", "API", "SQL", "OKTA_LOGIN"], typing.Any +] diff --git a/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_actor_type.py b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_actor_type.py new file mode 100644 index 00000000..4a5a96f1 --- /dev/null +++ b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_actor_type.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +AuditServiceListAuditEventsRequestFilterOpsContextActorType = typing.Union[ + typing.Literal["NONE", "USER", "SERVICE_ACCOUNT"], typing.Any +] diff --git a/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_auth_mode.py b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_auth_mode.py new file mode 100644 index 00000000..f542f677 --- /dev/null +++ b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_context_auth_mode.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +AuditServiceListAuditEventsRequestFilterOpsContextAuthMode = typing.Union[ + typing.Literal["AUTH_NONE", "OKTA_JWT", "SERVICE_ACCOUNT_JWT", "PAT_JWT"], typing.Any +] diff --git a/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_resource_type.py b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_resource_type.py new file mode 100644 index 00000000..610aa1e6 --- /dev/null +++ b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_filter_ops_resource_type.py @@ -0,0 +1,39 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +AuditServiceListAuditEventsRequestFilterOpsResourceType = typing.Union[ + typing.Literal[ + "NONE_API", + "ACCOUNT", + "AUDIT", + "BASE_DATA_TYPE", + "FIELD_TEMPLATE", + "FILE", + "KEY", + "POLICY", + "PROTO_PARSE", + "RECORD", + "ROLE", + "RULE", + "SECRET", + "SERVICE_ACCOUNT", + "TOKEN", + "USER", + "VAULT", + "VAULT_TEMPLATE", + "WORKSPACE", + "TABLE", + "POLICY_TEMPLATE", + "MEMBER", + "TAG", + "CONNECTION", + "MIGRATION", + "SCHEDULED_JOB", + "JOB", + "COLUMN_NAME", + "NETWORK_TOKEN", + "SUBSCRIPTION", + ], + typing.Any, +] diff --git a/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_sort_ops_order_by.py b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_sort_ops_order_by.py new file mode 100644 index 00000000..48a79484 --- /dev/null +++ b/skyflow/generated/rest/audit/types/audit_service_list_audit_events_request_sort_ops_order_by.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +AuditServiceListAuditEventsRequestSortOpsOrderBy = typing.Union[typing.Literal["ASCENDING", "DESCENDING"], typing.Any] diff --git a/skyflow/generated/rest/authentication/__init__.py b/skyflow/generated/rest/authentication/__init__.py new file mode 100644 index 00000000..f3ea2659 --- /dev/null +++ b/skyflow/generated/rest/authentication/__init__.py @@ -0,0 +1,2 @@ +# This file was auto-generated by Fern from our API Definition. + diff --git a/skyflow/generated/rest/authentication/client.py b/skyflow/generated/rest/authentication/client.py new file mode 100644 index 00000000..c4825e27 --- /dev/null +++ b/skyflow/generated/rest/authentication/client.py @@ -0,0 +1,264 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from ..types.v_1_get_auth_token_response import V1GetAuthTokenResponse +from ..core.pydantic_utilities import parse_obj_as +from ..errors.bad_request_error import BadRequestError +from ..errors.unauthorized_error import UnauthorizedError +from ..errors.not_found_error import NotFoundError +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class AuthenticationClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def authentication_service_get_auth_token( + self, + *, + grant_type: str, + assertion: str, + subject_token: typing.Optional[str] = OMIT, + subject_token_type: typing.Optional[str] = OMIT, + requested_token_use: typing.Optional[str] = OMIT, + scope: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1GetAuthTokenResponse: + """ +

Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the Authorization header.

Note: For recommended ways to authenticate, see API authentication.

+ + Parameters + ---------- + grant_type : str + Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`. + + assertion : str + User-signed JWT token that contains the following fields:
  • iss: Issuer of the JWT.
  • key: Unique identifier for the key.
  • aud: Recipient the JWT is intended for.
  • exp: Time the JWT expires.
  • sub: Subject of the JWT.
  • ctx: (Optional) Value for Context-aware authorization.
+ + subject_token : typing.Optional[str] + Subject token. + + subject_token_type : typing.Optional[str] + Subject token type. + + requested_token_use : typing.Optional[str] + Token use type. Either `delegation` or `impersonation`. + + scope : typing.Optional[str] + Subset of available roles to associate with the requested token. Uses the format "role:\ role:\". + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1GetAuthTokenResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.authentication.authentication_service_get_auth_token( + grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer", + assertion="eyLhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNzIjoiY29tcGFueSIsImV4cCI6MTYxNTE5MzgwNywiaWF0IjoxNjE1MTY1MDQwLCJhdWQiOiKzb21lYXVkaWVuY2UifQ.4pcPyMDQ9o1PSyXnrXCjTwXyr4BSezdI1AVTmud2fU3", + ) + """ + _response = self._client_wrapper.httpx_client.request( + "v1/auth/sa/oauth/token", + method="POST", + json={ + "grant_type": grant_type, + "assertion": assertion, + "subject_token": subject_token, + "subject_token_type": subject_token_type, + "requested_token_use": requested_token_use, + "scope": scope, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1GetAuthTokenResponse, + parse_obj_as( + type_=V1GetAuthTokenResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 400: + raise BadRequestError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 401: + raise UnauthorizedError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + +class AsyncAuthenticationClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def authentication_service_get_auth_token( + self, + *, + grant_type: str, + assertion: str, + subject_token: typing.Optional[str] = OMIT, + subject_token_type: typing.Optional[str] = OMIT, + requested_token_use: typing.Optional[str] = OMIT, + scope: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1GetAuthTokenResponse: + """ +

Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the Authorization header.

Note: For recommended ways to authenticate, see API authentication.

+ + Parameters + ---------- + grant_type : str + Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`. + + assertion : str + User-signed JWT token that contains the following fields:
  • iss: Issuer of the JWT.
  • key: Unique identifier for the key.
  • aud: Recipient the JWT is intended for.
  • exp: Time the JWT expires.
  • sub: Subject of the JWT.
  • ctx: (Optional) Value for Context-aware authorization.
+ + subject_token : typing.Optional[str] + Subject token. + + subject_token_type : typing.Optional[str] + Subject token type. + + requested_token_use : typing.Optional[str] + Token use type. Either `delegation` or `impersonation`. + + scope : typing.Optional[str] + Subset of available roles to associate with the requested token. Uses the format "role:\ role:\". + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1GetAuthTokenResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.authentication.authentication_service_get_auth_token( + grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer", + assertion="eyLhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNzIjoiY29tcGFueSIsImV4cCI6MTYxNTE5MzgwNywiaWF0IjoxNjE1MTY1MDQwLCJhdWQiOiKzb21lYXVkaWVuY2UifQ.4pcPyMDQ9o1PSyXnrXCjTwXyr4BSezdI1AVTmud2fU3", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + "v1/auth/sa/oauth/token", + method="POST", + json={ + "grant_type": grant_type, + "assertion": assertion, + "subject_token": subject_token, + "subject_token_type": subject_token_type, + "requested_token_use": requested_token_use, + "scope": scope, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1GetAuthTokenResponse, + parse_obj_as( + type_=V1GetAuthTokenResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 400: + raise BadRequestError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 401: + raise UnauthorizedError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/bin_lookup/__init__.py b/skyflow/generated/rest/bin_lookup/__init__.py new file mode 100644 index 00000000..f3ea2659 --- /dev/null +++ b/skyflow/generated/rest/bin_lookup/__init__.py @@ -0,0 +1,2 @@ +# This file was auto-generated by Fern from our API Definition. + diff --git a/skyflow/generated/rest/bin_lookup/client.py b/skyflow/generated/rest/bin_lookup/client.py new file mode 100644 index 00000000..58d30c51 --- /dev/null +++ b/skyflow/generated/rest/bin_lookup/client.py @@ -0,0 +1,204 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from ..core.client_wrapper import SyncClientWrapper +from ..types.v_1_vault_schema_config import V1VaultSchemaConfig +from ..core.request_options import RequestOptions +from ..types.v_1_bin_list_response import V1BinListResponse +from ..core.serialization import convert_and_respect_annotation_metadata +from ..core.pydantic_utilities import parse_obj_as +from ..errors.not_found_error import NotFoundError +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class BinLookupClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def bin_list_service_list_cards_of_bin( + self, + *, + fields: typing.Optional[typing.Sequence[str]] = OMIT, + bin: typing.Optional[str] = OMIT, + vault_schema_config: typing.Optional[V1VaultSchemaConfig] = OMIT, + skyflow_id: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BinListResponse: + """ + Note: This endpoint is in beta and subject to change.

Returns the specified card metadata. + + Parameters + ---------- + fields : typing.Optional[typing.Sequence[str]] + Fields to return. If not specified, all fields are returned. + + bin : typing.Optional[str] + BIN of the card. + + vault_schema_config : typing.Optional[V1VaultSchemaConfig] + + skyflow_id : typing.Optional[str] + skyflow_id of the record. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BinListResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.bin_lookup.bin_list_service_list_cards_of_bin( + bin="012345", + ) + """ + _response = self._client_wrapper.httpx_client.request( + "v1/card_lookup", + method="POST", + json={ + "fields": fields, + "BIN": bin, + "vault_schema_config": convert_and_respect_annotation_metadata( + object_=vault_schema_config, annotation=V1VaultSchemaConfig, direction="write" + ), + "skyflow_id": skyflow_id, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BinListResponse, + parse_obj_as( + type_=V1BinListResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + +class AsyncBinLookupClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def bin_list_service_list_cards_of_bin( + self, + *, + fields: typing.Optional[typing.Sequence[str]] = OMIT, + bin: typing.Optional[str] = OMIT, + vault_schema_config: typing.Optional[V1VaultSchemaConfig] = OMIT, + skyflow_id: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BinListResponse: + """ + Note: This endpoint is in beta and subject to change.

Returns the specified card metadata. + + Parameters + ---------- + fields : typing.Optional[typing.Sequence[str]] + Fields to return. If not specified, all fields are returned. + + bin : typing.Optional[str] + BIN of the card. + + vault_schema_config : typing.Optional[V1VaultSchemaConfig] + + skyflow_id : typing.Optional[str] + skyflow_id of the record. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BinListResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.bin_lookup.bin_list_service_list_cards_of_bin( + bin="012345", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + "v1/card_lookup", + method="POST", + json={ + "fields": fields, + "BIN": bin, + "vault_schema_config": convert_and_respect_annotation_metadata( + object_=vault_schema_config, annotation=V1VaultSchemaConfig, direction="write" + ), + "skyflow_id": skyflow_id, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BinListResponse, + parse_obj_as( + type_=V1BinListResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/client.py b/skyflow/generated/rest/client.py new file mode 100644 index 00000000..7064d444 --- /dev/null +++ b/skyflow/generated/rest/client.py @@ -0,0 +1,160 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from .environment import SkyflowEnvironment +import httpx +from .core.client_wrapper import SyncClientWrapper +from .audit.client import AuditClient +from .bin_lookup.client import BinLookupClient +from .records.client import RecordsClient +from .tokens.client import TokensClient +from .query.client import QueryClient +from .authentication.client import AuthenticationClient +from .core.client_wrapper import AsyncClientWrapper +from .audit.client import AsyncAuditClient +from .bin_lookup.client import AsyncBinLookupClient +from .records.client import AsyncRecordsClient +from .tokens.client import AsyncTokensClient +from .query.client import AsyncQueryClient +from .authentication.client import AsyncAuthenticationClient + + +class Skyflow: + """ + Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions. + + Parameters + ---------- + base_url : typing.Optional[str] + The base url to use for requests from the client. + + environment : SkyflowEnvironment + The environment to use for requests from the client. from .environment import SkyflowEnvironment + + + + Defaults to SkyflowEnvironment.PRODUCTION + + + + token : typing.Union[str, typing.Callable[[], str]] + timeout : typing.Optional[float] + The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced. + + follow_redirects : typing.Optional[bool] + Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in. + + httpx_client : typing.Optional[httpx.Client] + The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + """ + + def __init__( + self, + *, + base_url: typing.Optional[str] = None, + environment: SkyflowEnvironment = SkyflowEnvironment.PRODUCTION, + token: typing.Union[str, typing.Callable[[], str]], + timeout: typing.Optional[float] = None, + follow_redirects: typing.Optional[bool] = True, + httpx_client: typing.Optional[httpx.Client] = None, + ): + _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + self._client_wrapper = SyncClientWrapper( + base_url=_get_base_url(base_url=base_url, environment=environment), + token=token, + httpx_client=httpx_client + if httpx_client is not None + else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + if follow_redirects is not None + else httpx.Client(timeout=_defaulted_timeout), + timeout=_defaulted_timeout, + ) + self.audit = AuditClient(client_wrapper=self._client_wrapper) + self.bin_lookup = BinLookupClient(client_wrapper=self._client_wrapper) + self.records = RecordsClient(client_wrapper=self._client_wrapper) + self.tokens = TokensClient(client_wrapper=self._client_wrapper) + self.query = QueryClient(client_wrapper=self._client_wrapper) + self.authentication = AuthenticationClient(client_wrapper=self._client_wrapper) + + +class AsyncSkyflow: + """ + Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions. + + Parameters + ---------- + base_url : typing.Optional[str] + The base url to use for requests from the client. + + environment : SkyflowEnvironment + The environment to use for requests from the client. from .environment import SkyflowEnvironment + + + + Defaults to SkyflowEnvironment.PRODUCTION + + + + token : typing.Union[str, typing.Callable[[], str]] + timeout : typing.Optional[float] + The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced. + + follow_redirects : typing.Optional[bool] + Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in. + + httpx_client : typing.Optional[httpx.AsyncClient] + The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration. + + Examples + -------- + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + """ + + def __init__( + self, + *, + base_url: typing.Optional[str] = None, + environment: SkyflowEnvironment = SkyflowEnvironment.PRODUCTION, + token: typing.Union[str, typing.Callable[[], str]], + timeout: typing.Optional[float] = None, + follow_redirects: typing.Optional[bool] = True, + httpx_client: typing.Optional[httpx.AsyncClient] = None, + ): + _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + self._client_wrapper = AsyncClientWrapper( + base_url=_get_base_url(base_url=base_url, environment=environment), + token=token, + httpx_client=httpx_client + if httpx_client is not None + else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + if follow_redirects is not None + else httpx.AsyncClient(timeout=_defaulted_timeout), + timeout=_defaulted_timeout, + ) + self.audit = AsyncAuditClient(client_wrapper=self._client_wrapper) + self.bin_lookup = AsyncBinLookupClient(client_wrapper=self._client_wrapper) + self.records = AsyncRecordsClient(client_wrapper=self._client_wrapper) + self.tokens = AsyncTokensClient(client_wrapper=self._client_wrapper) + self.query = AsyncQueryClient(client_wrapper=self._client_wrapper) + self.authentication = AsyncAuthenticationClient(client_wrapper=self._client_wrapper) + + +def _get_base_url(*, base_url: typing.Optional[str] = None, environment: SkyflowEnvironment) -> str: + if base_url is not None: + return base_url + elif environment is not None: + return environment.value + else: + raise Exception("Please pass in either base_url or environment to construct the client") diff --git a/skyflow/generated/rest/configuration.py b/skyflow/generated/rest/configuration.py deleted file mode 100644 index 5d983650..00000000 --- a/skyflow/generated/rest/configuration.py +++ /dev/null @@ -1,464 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -import copy -import logging -from logging import FileHandler -import multiprocessing -import sys -from typing import Optional -import urllib3 - -import http.client as httplib - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' -} - -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: - """ - - _default = None - - def __init__(self, host=None, - api_key=None, api_key_prefix=None, - username=None, password=None, - access_token=None, - server_index=None, server_variables=None, - server_operation_index=None, server_operation_variables=None, - ignore_operation_servers=False, - ssl_ca_cert=None, - retries=None, - *, - debug: Optional[bool] = None - ) -> None: - """Constructor - """ - self._base_path = "https://identifier.vault.skyflowapis.com" 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("skyflow.generated.rest") - 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): - 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, value): - object.__setattr__(self, name, value) - - @classmethod - def set_default(cls, default): - """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): - """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): - """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 = Configuration() - return cls._default - - @property - def logger_file(self): - """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): - """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): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """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): - """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): - """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, alias=None): - """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 - - def get_basic_auth_token(self): - """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): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - auth = {} - if self.access_token is not None: - auth['Bearer'] = { - 'type': 'bearer', - 'in': 'header', - 'format': 'JWT', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - } - return auth - - def to_debug_report(self): - """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: v1\n"\ - "SDK Package Version: 1.0.0".\ - format(env=sys.platform, pyversion=sys.version) - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [ - { - 'url': "https://identifier.vault.skyflowapis.com", - 'description': "Production", - }, - { - 'url': "https://identifier.vault.skyflowapis-preview.com", - 'description': "Sandbox", - } - ] - - def get_host_from_settings(self, index, variables=None, servers=None): - """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): - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) - - @host.setter - def host(self, value): - """Fix base path.""" - self._base_path = value - self.server_index = None diff --git a/skyflow/generated/rest/core/__init__.py b/skyflow/generated/rest/core/__init__.py new file mode 100644 index 00000000..f03aecbf --- /dev/null +++ b/skyflow/generated/rest/core/__init__.py @@ -0,0 +1,47 @@ +# This file was auto-generated by Fern from our API Definition. + +from .api_error import ApiError +from .client_wrapper import AsyncClientWrapper, BaseClientWrapper, SyncClientWrapper +from .datetime_utils import serialize_datetime +from .file import File, convert_file_dict_to_httpx_tuples, with_content_type +from .http_client import AsyncHttpClient, HttpClient +from .jsonable_encoder import jsonable_encoder +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + UniversalBaseModel, + UniversalRootModel, + parse_obj_as, + universal_field_validator, + universal_root_validator, + update_forward_refs, +) +from .query_encoder import encode_query +from .remove_none_from_dict import remove_none_from_dict +from .request_options import RequestOptions +from .serialization import FieldMetadata, convert_and_respect_annotation_metadata + +__all__ = [ + "ApiError", + "AsyncClientWrapper", + "AsyncHttpClient", + "BaseClientWrapper", + "FieldMetadata", + "File", + "HttpClient", + "IS_PYDANTIC_V2", + "RequestOptions", + "SyncClientWrapper", + "UniversalBaseModel", + "UniversalRootModel", + "convert_and_respect_annotation_metadata", + "convert_file_dict_to_httpx_tuples", + "encode_query", + "jsonable_encoder", + "parse_obj_as", + "remove_none_from_dict", + "serialize_datetime", + "universal_field_validator", + "universal_root_validator", + "update_forward_refs", + "with_content_type", +] diff --git a/skyflow/generated/rest/core/api_error.py b/skyflow/generated/rest/core/api_error.py new file mode 100644 index 00000000..2e9fc543 --- /dev/null +++ b/skyflow/generated/rest/core/api_error.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + + +class ApiError(Exception): + status_code: typing.Optional[int] + body: typing.Any + + def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + self.status_code = status_code + self.body = body + + def __str__(self) -> str: + return f"status_code: {self.status_code}, body: {self.body}" diff --git a/skyflow/generated/rest/core/client_wrapper.py b/skyflow/generated/rest/core/client_wrapper.py new file mode 100644 index 00000000..7177cf7c --- /dev/null +++ b/skyflow/generated/rest/core/client_wrapper.py @@ -0,0 +1,76 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +import httpx +from .http_client import HttpClient +from .http_client import AsyncHttpClient + + +class BaseClientWrapper: + def __init__( + self, + *, + token: typing.Union[str, typing.Callable[[], str]], + base_url: str, + timeout: typing.Optional[float] = None, + ): + self._token = token + self._base_url = base_url + self._timeout = timeout + + def get_headers(self) -> typing.Dict[str, str]: + headers: typing.Dict[str, str] = { + "X-Fern-Language": "Python", + "X-Fern-SDK-Name": "skyflow", + "X-Fern-SDK-Version": "1.15.2", + } + headers["Authorization"] = f"Bearer {self._get_token()}" + return headers + + def _get_token(self) -> str: + if isinstance(self._token, str): + return self._token + else: + return self._token() + + def get_base_url(self) -> str: + return self._base_url + + def get_timeout(self) -> typing.Optional[float]: + return self._timeout + + +class SyncClientWrapper(BaseClientWrapper): + def __init__( + self, + *, + token: typing.Union[str, typing.Callable[[], str]], + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): + super().__init__(token=token, base_url=base_url, timeout=timeout) + self.httpx_client = HttpClient( + httpx_client=httpx_client, + base_headers=self.get_headers, + base_timeout=self.get_timeout, + base_url=self.get_base_url, + ) + + +class AsyncClientWrapper(BaseClientWrapper): + def __init__( + self, + *, + token: typing.Union[str, typing.Callable[[], str]], + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): + super().__init__(token=token, base_url=base_url, timeout=timeout) + self.httpx_client = AsyncHttpClient( + httpx_client=httpx_client, + base_headers=self.get_headers, + base_timeout=self.get_timeout, + base_url=self.get_base_url, + ) diff --git a/skyflow/generated/rest/core/datetime_utils.py b/skyflow/generated/rest/core/datetime_utils.py new file mode 100644 index 00000000..7c9864a9 --- /dev/null +++ b/skyflow/generated/rest/core/datetime_utils.py @@ -0,0 +1,28 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt + + +def serialize_datetime(v: dt.datetime) -> str: + """ + Serialize a datetime including timezone info. + + Uses the timezone info provided if present, otherwise uses the current runtime's timezone info. + + UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00. + """ + + def _serialize_zoned_datetime(v: dt.datetime) -> str: + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + # UTC is a special case where we use "Z" at the end instead of "+00:00" + return v.isoformat().replace("+00:00", "Z") + else: + # Delegate to the typical +/- offset format + return v.isoformat() + + if v.tzinfo is not None: + return _serialize_zoned_datetime(v) + else: + local_tz = dt.datetime.now().astimezone().tzinfo + localized_dt = v.replace(tzinfo=local_tz) + return _serialize_zoned_datetime(localized_dt) diff --git a/skyflow/generated/rest/core/file.py b/skyflow/generated/rest/core/file.py new file mode 100644 index 00000000..44b0d27c --- /dev/null +++ b/skyflow/generated/rest/core/file.py @@ -0,0 +1,67 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import IO, Dict, List, Mapping, Optional, Tuple, Union, cast + +# File typing inspired by the flexibility of types within the httpx library +# https://github.com/encode/httpx/blob/master/httpx/_types.py +FileContent = Union[IO[bytes], bytes, str] +File = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[ + Optional[str], + FileContent, + Optional[str], + Mapping[str, str], + ], +] + + +def convert_file_dict_to_httpx_tuples( + d: Dict[str, Union[File, List[File]]], +) -> List[Tuple[str, File]]: + """ + The format we use is a list of tuples, where the first element is the + name of the file and the second is the file object. Typically HTTPX wants + a dict, but to be able to send lists of files, you have to use the list + approach (which also works for non-lists) + https://github.com/encode/httpx/pull/1032 + """ + + httpx_tuples = [] + for key, file_like in d.items(): + if isinstance(file_like, list): + for file_like_item in file_like: + httpx_tuples.append((key, file_like_item)) + else: + httpx_tuples.append((key, file_like)) + return httpx_tuples + + +def with_content_type(*, file: File, default_content_type: str) -> File: + """ + This function resolves to the file's content type, if provided, and defaults + to the default_content_type value if not. + """ + if isinstance(file, tuple): + if len(file) == 2: + filename, content = cast(Tuple[Optional[str], FileContent], file) # type: ignore + return (filename, content, default_content_type) + elif len(file) == 3: + filename, content, file_content_type = cast(Tuple[Optional[str], FileContent, Optional[str]], file) # type: ignore + out_content_type = file_content_type or default_content_type + return (filename, content, out_content_type) + elif len(file) == 4: + filename, content, file_content_type, headers = cast( # type: ignore + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], file + ) + out_content_type = file_content_type or default_content_type + return (filename, content, out_content_type, headers) + else: + raise ValueError(f"Unexpected tuple length: {len(file)}") + return (None, file, default_content_type) diff --git a/skyflow/generated/rest/core/http_client.py b/skyflow/generated/rest/core/http_client.py new file mode 100644 index 00000000..275a54cc --- /dev/null +++ b/skyflow/generated/rest/core/http_client.py @@ -0,0 +1,499 @@ +# This file was auto-generated by Fern from our API Definition. + +import asyncio +import email.utils +import json +import re +import time +import typing +import urllib.parse +from contextlib import asynccontextmanager, contextmanager +from random import random + +import httpx + +from .file import File, convert_file_dict_to_httpx_tuples +from .jsonable_encoder import jsonable_encoder +from .query_encoder import encode_query +from .remove_none_from_dict import remove_none_from_dict +from .request_options import RequestOptions + +INITIAL_RETRY_DELAY_SECONDS = 0.5 +MAX_RETRY_DELAY_SECONDS = 10 +MAX_RETRY_DELAY_SECONDS_FROM_HEADER = 30 + + +def _parse_retry_after(response_headers: httpx.Headers) -> typing.Optional[float]: + """ + This function parses the `Retry-After` header in a HTTP response and returns the number of seconds to wait. + + Inspired by the urllib3 retry implementation. + """ + retry_after_ms = response_headers.get("retry-after-ms") + if retry_after_ms is not None: + try: + return int(retry_after_ms) / 1000 if retry_after_ms > 0 else 0 + except Exception: + pass + + retry_after = response_headers.get("retry-after") + if retry_after is None: + return None + + # Attempt to parse the header as an int. + if re.match(r"^\s*[0-9]+\s*$", retry_after): + seconds = float(retry_after) + # Fallback to parsing it as a date. + else: + retry_date_tuple = email.utils.parsedate_tz(retry_after) + if retry_date_tuple is None: + return None + if retry_date_tuple[9] is None: # Python 2 + # Assume UTC if no timezone was specified + # On Python2.7, parsedate_tz returns None for a timezone offset + # instead of 0 if no timezone is given, where mktime_tz treats + # a None timezone offset as local time. + retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:] + + retry_date = email.utils.mktime_tz(retry_date_tuple) + seconds = retry_date - time.time() + + if seconds < 0: + seconds = 0 + + return seconds + + +def _retry_timeout(response: httpx.Response, retries: int) -> float: + """ + Determine the amount of time to wait before retrying a request. + This function begins by trying to parse a retry-after header from the response, and then proceeds to use exponential backoff + with a jitter to determine the number of seconds to wait. + """ + + # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says. + retry_after = _parse_retry_after(response.headers) + if retry_after is not None and retry_after <= MAX_RETRY_DELAY_SECONDS_FROM_HEADER: + return retry_after + + # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. + retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + + # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. + timeout = retry_delay * (1 - 0.25 * random()) + return timeout if timeout >= 0 else 0 + + +def _should_retry(response: httpx.Response) -> bool: + retryable_400s = [429, 408, 409] + return response.status_code >= 500 or response.status_code in retryable_400s + + +def remove_omit_from_dict( + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], +) -> typing.Dict[str, typing.Any]: + if omit is None: + return original + new: typing.Dict[str, typing.Any] = {} + for key, value in original.items(): + if value is not omit: + new[key] = value + return new + + +def maybe_filter_request_body( + data: typing.Optional[typing.Any], + request_options: typing.Optional[RequestOptions], + omit: typing.Optional[typing.Any], +) -> typing.Optional[typing.Any]: + if data is None: + return ( + jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + if request_options is not None + else None + ) + elif not isinstance(data, typing.Mapping): + data_content = jsonable_encoder(data) + else: + data_content = { + **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore + **( + jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + if request_options is not None + else {} + ), + } + return data_content + + +# Abstracted out for testing purposes +def get_request_body( + *, + json: typing.Optional[typing.Any], + data: typing.Optional[typing.Any], + request_options: typing.Optional[RequestOptions], + omit: typing.Optional[typing.Any], +) -> typing.Tuple[typing.Optional[typing.Any], typing.Optional[typing.Any]]: + json_body = None + data_body = None + if data is not None: + data_body = maybe_filter_request_body(data, request_options, omit) + else: + # If both data and json are None, we send json data in the event extra properties are specified + json_body = maybe_filter_request_body(json, request_options, omit) + + # If you have an empty JSON body, you should just send None + return (json_body if json_body != {} else None), data_body if data_body != {} else None + + +class HttpClient: + def __init__( + self, + *, + httpx_client: httpx.Client, + base_timeout: typing.Callable[[], typing.Optional[float]], + base_headers: typing.Callable[[], typing.Dict[str, str]], + base_url: typing.Optional[typing.Callable[[], str]] = None, + ): + self.base_url = base_url + self.base_timeout = base_timeout + self.base_headers = base_headers + self.httpx_client = httpx_client + + def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: + base_url = maybe_base_url + if self.base_url is not None and base_url is None: + base_url = self.base_url() + + if base_url is None: + raise ValueError("A base_url is required to make this request, please provide one and try again.") + return base_url + + def request( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 2, + omit: typing.Optional[typing.Any] = None, + ) -> httpx.Response: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + response = self.httpx_client.request( + method=method, + url=urllib.parse.urljoin(f"{base_url}/", path), + headers=jsonable_encoder( + remove_none_from_dict( + { + **self.base_headers(), + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + } + ) + ), + params=encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + }, + omit, + ) + ) + ) + ), + json=json_body, + data=data_body, + content=content, + files=( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if (files is not None and files is not omit) + else None + ), + timeout=timeout, + ) + + max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + if _should_retry(response=response): + if max_retries > retries: + time.sleep(_retry_timeout(response=response, retries=retries)) + return self.request( + path=path, + method=method, + base_url=base_url, + params=params, + json=json, + content=content, + files=files, + headers=headers, + request_options=request_options, + retries=retries + 1, + omit=omit, + ) + + return response + + @contextmanager + def stream( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 2, + omit: typing.Optional[typing.Any] = None, + ) -> typing.Iterator[httpx.Response]: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + with self.httpx_client.stream( + method=method, + url=urllib.parse.urljoin(f"{base_url}/", path), + headers=jsonable_encoder( + remove_none_from_dict( + { + **self.base_headers(), + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) if request_options is not None else {}), + } + ) + ), + params=encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) + if request_options is not None + else {} + ), + }, + omit, + ) + ) + ) + ), + json=json_body, + data=data_body, + content=content, + files=( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if (files is not None and files is not omit) + else None + ), + timeout=timeout, + ) as stream: + yield stream + + +class AsyncHttpClient: + def __init__( + self, + *, + httpx_client: httpx.AsyncClient, + base_timeout: typing.Callable[[], typing.Optional[float]], + base_headers: typing.Callable[[], typing.Dict[str, str]], + base_url: typing.Optional[typing.Callable[[], str]] = None, + ): + self.base_url = base_url + self.base_timeout = base_timeout + self.base_headers = base_headers + self.httpx_client = httpx_client + + def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: + base_url = maybe_base_url + if self.base_url is not None and base_url is None: + base_url = self.base_url() + + if base_url is None: + raise ValueError("A base_url is required to make this request, please provide one and try again.") + return base_url + + async def request( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 2, + omit: typing.Optional[typing.Any] = None, + ) -> httpx.Response: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + # Add the input to each of these and do None-safety checks + response = await self.httpx_client.request( + method=method, + url=urllib.parse.urljoin(f"{base_url}/", path), + headers=jsonable_encoder( + remove_none_from_dict( + { + **self.base_headers(), + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + } + ) + ), + params=encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + }, + omit, + ) + ) + ) + ), + json=json_body, + data=data_body, + content=content, + files=( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if files is not None + else None + ), + timeout=timeout, + ) + + max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + if _should_retry(response=response): + if max_retries > retries: + await asyncio.sleep(_retry_timeout(response=response, retries=retries)) + return await self.request( + path=path, + method=method, + base_url=base_url, + params=params, + json=json, + content=content, + files=files, + headers=headers, + request_options=request_options, + retries=retries + 1, + omit=omit, + ) + return response + + @asynccontextmanager + async def stream( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 2, + omit: typing.Optional[typing.Any] = None, + ) -> typing.AsyncIterator[httpx.Response]: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + async with self.httpx_client.stream( + method=method, + url=urllib.parse.urljoin(f"{base_url}/", path), + headers=jsonable_encoder( + remove_none_from_dict( + { + **self.base_headers(), + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) if request_options is not None else {}), + } + ) + ), + params=encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) + if request_options is not None + else {} + ), + }, + omit=omit, + ) + ) + ) + ), + json=json_body, + data=data_body, + content=content, + files=( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if files is not None + else None + ), + timeout=timeout, + ) as stream: + yield stream diff --git a/skyflow/generated/rest/core/jsonable_encoder.py b/skyflow/generated/rest/core/jsonable_encoder.py new file mode 100644 index 00000000..1b631e90 --- /dev/null +++ b/skyflow/generated/rest/core/jsonable_encoder.py @@ -0,0 +1,101 @@ +# This file was auto-generated by Fern from our API Definition. + +""" +jsonable_encoder converts a Python object to a JSON-friendly dict +(e.g. datetimes to strings, Pydantic models to dicts). + +Taken from FastAPI, and made a bit simpler +https://github.com/tiangolo/fastapi/blob/master/fastapi/encoders.py +""" + +import base64 +import dataclasses +import datetime as dt +from enum import Enum +from pathlib import PurePath +from types import GeneratorType +from typing import Any, Callable, Dict, List, Optional, Set, Union + +import pydantic + +from .datetime_utils import serialize_datetime +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) + +SetIntStr = Set[Union[int, str]] +DictIntStrAny = Dict[Union[int, str], Any] + + +def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: + custom_encoder = custom_encoder or {} + if custom_encoder: + if type(obj) in custom_encoder: + return custom_encoder[type(obj)](obj) + else: + for encoder_type, encoder_instance in custom_encoder.items(): + if isinstance(obj, encoder_type): + return encoder_instance(obj) + if isinstance(obj, pydantic.BaseModel): + if IS_PYDANTIC_V2: + encoder = getattr(obj.model_config, "json_encoders", {}) # type: ignore # Pydantic v2 + else: + encoder = getattr(obj.__config__, "json_encoders", {}) # type: ignore # Pydantic v1 + if custom_encoder: + encoder.update(custom_encoder) + obj_dict = obj.dict(by_alias=True) + if "__root__" in obj_dict: + obj_dict = obj_dict["__root__"] + if "root" in obj_dict: + obj_dict = obj_dict["root"] + return jsonable_encoder(obj_dict, custom_encoder=encoder) + if dataclasses.is_dataclass(obj): + obj_dict = dataclasses.asdict(obj) # type: ignore + return jsonable_encoder(obj_dict, custom_encoder=custom_encoder) + if isinstance(obj, bytes): + return base64.b64encode(obj).decode("utf-8") + if isinstance(obj, Enum): + return obj.value + if isinstance(obj, PurePath): + return str(obj) + if isinstance(obj, (str, int, float, type(None))): + return obj + if isinstance(obj, dt.datetime): + return serialize_datetime(obj) + if isinstance(obj, dt.date): + return str(obj) + if isinstance(obj, dict): + encoded_dict = {} + allowed_keys = set(obj.keys()) + for key, value in obj.items(): + if key in allowed_keys: + encoded_key = jsonable_encoder(key, custom_encoder=custom_encoder) + encoded_value = jsonable_encoder(value, custom_encoder=custom_encoder) + encoded_dict[encoded_key] = encoded_value + return encoded_dict + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)): + encoded_list = [] + for item in obj: + encoded_list.append(jsonable_encoder(item, custom_encoder=custom_encoder)) + return encoded_list + + def fallback_serializer(o: Any) -> Any: + attempt_encode = encode_by_type(o) + if attempt_encode is not None: + return attempt_encode + + try: + data = dict(o) + except Exception as e: + errors: List[Exception] = [] + errors.append(e) + try: + data = vars(o) + except Exception as e: + errors.append(e) + raise ValueError(errors) from e + return jsonable_encoder(data, custom_encoder=custom_encoder) + + return to_jsonable_with_fallback(obj, fallback_serializer) diff --git a/skyflow/generated/rest/core/pydantic_utilities.py b/skyflow/generated/rest/core/pydantic_utilities.py new file mode 100644 index 00000000..ca1f4792 --- /dev/null +++ b/skyflow/generated/rest/core/pydantic_utilities.py @@ -0,0 +1,296 @@ +# This file was auto-generated by Fern from our API Definition. + +# nopycln: file +import datetime as dt +import typing +from collections import defaultdict + +import typing_extensions + +import pydantic + +from .datetime_utils import serialize_datetime +from .serialization import convert_and_respect_annotation_metadata + +IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.") + +if IS_PYDANTIC_V2: + # isort will try to reformat the comments on these imports, which breaks mypy + # isort: off + from pydantic.v1.datetime_parse import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 + parse_date as parse_date, + ) + from pydantic.v1.datetime_parse import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + parse_datetime as parse_datetime, + ) + from pydantic.v1.json import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 + ENCODERS_BY_TYPE as encoders_by_type, + ) + from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 + get_args as get_args, + ) + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_literal_type as is_literal_type, + ) + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) + from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 +else: + from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 + from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore # Pydantic v1 + from pydantic.fields import ModelField as ModelField # type: ignore # Pydantic v1 + from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore # Pydantic v1 + from pydantic.typing import get_args as get_args # type: ignore # Pydantic v1 + from pydantic.typing import get_origin as get_origin # type: ignore # Pydantic v1 + from pydantic.typing import is_literal_type as is_literal_type # type: ignore # Pydantic v1 + from pydantic.typing import is_union as is_union # type: ignore # Pydantic v1 + + # isort: on + + +T = typing.TypeVar("T") +Model = typing.TypeVar("Model", bound=pydantic.BaseModel) + + +def parse_obj_as(type_: typing.Type[T], object_: typing.Any) -> T: + dealiased_object = convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read") + if IS_PYDANTIC_V2: + adapter = pydantic.TypeAdapter(type_) # type: ignore # Pydantic v2 + return adapter.validate_python(dealiased_object) + else: + return pydantic.parse_obj_as(type_, dealiased_object) + + +def to_jsonable_with_fallback( + obj: typing.Any, fallback_serializer: typing.Callable[[typing.Any], typing.Any] +) -> typing.Any: + if IS_PYDANTIC_V2: + from pydantic_core import to_jsonable_python + + return to_jsonable_python(obj, fallback=fallback_serializer) + else: + return fallback_serializer(obj) + + +class UniversalBaseModel(pydantic.BaseModel): + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + # Allow fields beginning with `model_` to be used in the model + protected_namespaces=(), + ) # type: ignore # Pydantic v2 + + @pydantic.model_serializer(mode="wrap", when_used="json") # type: ignore # Pydantic v2 + def serialize_model(self, handler: pydantic.SerializerFunctionWrapHandler) -> typing.Any: # type: ignore # Pydantic v2 + serialized = handler(self) + data = {k: serialize_datetime(v) if isinstance(v, dt.datetime) else v for k, v in serialized.items()} + return data + + else: + + class Config: + smart_union = True + json_encoders = {dt.datetime: serialize_datetime} + + @classmethod + def model_construct( + cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + ) -> "Model": + dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read") + return cls.construct(_fields_set, **dealiased_object) + + @classmethod + def construct( + cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + ) -> "Model": + dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read") + if IS_PYDANTIC_V2: + return super().model_construct(_fields_set, **dealiased_object) # type: ignore # Pydantic v2 + else: + return super().construct(_fields_set, **dealiased_object) + + def json(self, **kwargs: typing.Any) -> str: + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + if IS_PYDANTIC_V2: + return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 + else: + return super().json(**kwargs_with_defaults) + + def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: + """ + Override the default dict method to `exclude_unset` by default. This function patches + `exclude_unset` to work include fields within non-None default values. + """ + # Note: the logic here is multiplexed given the levers exposed in Pydantic V1 vs V2 + # Pydantic V1's .dict can be extremely slow, so we do not want to call it twice. + # + # We'd ideally do the same for Pydantic V2, but it shells out to a library to serialize models + # that we have less control over, and this is less intrusive than custom serializers for now. + if IS_PYDANTIC_V2: + kwargs_with_defaults_exclude_unset: typing.Any = { + **kwargs, + "by_alias": True, + "exclude_unset": True, + "exclude_none": False, + } + kwargs_with_defaults_exclude_none: typing.Any = { + **kwargs, + "by_alias": True, + "exclude_none": True, + "exclude_unset": False, + } + dict_dump = deep_union_pydantic_dicts( + super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore # Pydantic v2 + super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore # Pydantic v2 + ) + + else: + _fields_set = self.__fields_set__.copy() + + fields = _get_model_fields(self.__class__) + for name, field in fields.items(): + if name not in _fields_set: + default = _get_field_default(field) + + # If the default values are non-null act like they've been set + # This effectively allows exclude_unset to work like exclude_none where + # the latter passes through intentionally set none values. + if default is not None or ("exclude_unset" in kwargs and not kwargs["exclude_unset"]): + _fields_set.add(name) + + if default is not None: + self.__fields_set__.add(name) + + kwargs_with_defaults_exclude_unset_include_fields: typing.Any = { + "by_alias": True, + "exclude_unset": True, + "include": _fields_set, + **kwargs, + } + + dict_dump = super().dict(**kwargs_with_defaults_exclude_unset_include_fields) + + return convert_and_respect_annotation_metadata(object_=dict_dump, annotation=self.__class__, direction="write") + + +def _union_list_of_pydantic_dicts( + source: typing.List[typing.Any], destination: typing.List[typing.Any] +) -> typing.List[typing.Any]: + converted_list: typing.List[typing.Any] = [] + for i, item in enumerate(source): + destination_value = destination[i] # type: ignore + if isinstance(item, dict): + converted_list.append(deep_union_pydantic_dicts(item, destination_value)) + elif isinstance(item, list): + converted_list.append(_union_list_of_pydantic_dicts(item, destination_value)) + else: + converted_list.append(item) + return converted_list + + +def deep_union_pydantic_dicts( + source: typing.Dict[str, typing.Any], destination: typing.Dict[str, typing.Any] +) -> typing.Dict[str, typing.Any]: + for key, value in source.items(): + node = destination.setdefault(key, {}) + if isinstance(value, dict): + deep_union_pydantic_dicts(value, node) + # Note: we do not do this same processing for sets given we do not have sets of models + # and given the sets are unordered, the processing of the set and matching objects would + # be non-trivial. + elif isinstance(value, list): + destination[key] = _union_list_of_pydantic_dicts(value, node) + else: + destination[key] = value + + return destination + + +if IS_PYDANTIC_V2: + + class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore # Pydantic v2 + pass + + UniversalRootModel: typing_extensions.TypeAlias = V2RootModel # type: ignore +else: + UniversalRootModel: typing_extensions.TypeAlias = UniversalBaseModel # type: ignore + + +def encode_by_type(o: typing.Any) -> typing.Any: + encoders_by_class_tuples: typing.Dict[typing.Callable[[typing.Any], typing.Any], typing.Tuple[typing.Any, ...]] = ( + defaultdict(tuple) + ) + for type_, encoder in encoders_by_type.items(): + encoders_by_class_tuples[encoder] += (type_,) + + if type(o) in encoders_by_type: + return encoders_by_type[type(o)](o) + for encoder, classes_tuple in encoders_by_class_tuples.items(): + if isinstance(o, classes_tuple): + return encoder(o) + + +def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> None: + if IS_PYDANTIC_V2: + model.model_rebuild(raise_errors=False) # type: ignore # Pydantic v2 + else: + model.update_forward_refs(**localns) + + +# Mirrors Pydantic's internal typing +AnyCallable = typing.Callable[..., typing.Any] + + +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: + def decorator(func: AnyCallable) -> AnyCallable: + if IS_PYDANTIC_V2: + return pydantic.model_validator(mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + else: + return pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 + + return decorator + + +def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: + def decorator(func: AnyCallable) -> AnyCallable: + if IS_PYDANTIC_V2: + return pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + else: + return pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 + + return decorator + + +PydanticField = typing.Union[ModelField, pydantic.fields.FieldInfo] + + +def _get_model_fields( + model: typing.Type["Model"], +) -> typing.Mapping[str, PydanticField]: + if IS_PYDANTIC_V2: + return model.model_fields # type: ignore # Pydantic v2 + else: + return model.__fields__ # type: ignore # Pydantic v1 + + +def _get_field_default(field: PydanticField) -> typing.Any: + try: + value = field.get_default() # type: ignore # Pydantic < v1.10.15 + except: + value = field.default + if IS_PYDANTIC_V2: + from pydantic_core import PydanticUndefined + + if value == PydanticUndefined: + return None + return value + return value diff --git a/skyflow/generated/rest/core/query_encoder.py b/skyflow/generated/rest/core/query_encoder.py new file mode 100644 index 00000000..3183001d --- /dev/null +++ b/skyflow/generated/rest/core/query_encoder.py @@ -0,0 +1,58 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Any, Dict, List, Optional, Tuple + +import pydantic + + +# Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict +def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> List[Tuple[str, Any]]: + result = [] + for k, v in dict_flat.items(): + key = f"{key_prefix}[{k}]" if key_prefix is not None else k + if isinstance(v, dict): + result.extend(traverse_query_dict(v, key)) + elif isinstance(v, list): + for arr_v in v: + if isinstance(arr_v, dict): + result.extend(traverse_query_dict(arr_v, key)) + else: + result.append((key, arr_v)) + else: + result.append((key, v)) + return result + + +def single_query_encoder(query_key: str, query_value: Any) -> List[Tuple[str, Any]]: + if isinstance(query_value, pydantic.BaseModel) or isinstance(query_value, dict): + if isinstance(query_value, pydantic.BaseModel): + obj_dict = query_value.dict(by_alias=True) + else: + obj_dict = query_value + return traverse_query_dict(obj_dict, query_key) + elif isinstance(query_value, list): + encoded_values: List[Tuple[str, Any]] = [] + for value in query_value: + if isinstance(value, pydantic.BaseModel) or isinstance(value, dict): + if isinstance(value, pydantic.BaseModel): + obj_dict = value.dict(by_alias=True) + elif isinstance(value, dict): + obj_dict = value + + encoded_values.extend(single_query_encoder(query_key, obj_dict)) + else: + encoded_values.append((query_key, value)) + + return encoded_values + + return [(query_key, query_value)] + + +def encode_query(query: Optional[Dict[str, Any]]) -> Optional[List[Tuple[str, Any]]]: + if query is None: + return None + + encoded_query = [] + for k, v in query.items(): + encoded_query.extend(single_query_encoder(k, v)) + return encoded_query diff --git a/skyflow/generated/rest/core/remove_none_from_dict.py b/skyflow/generated/rest/core/remove_none_from_dict.py new file mode 100644 index 00000000..c2298143 --- /dev/null +++ b/skyflow/generated/rest/core/remove_none_from_dict.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Any, Dict, Mapping, Optional + + +def remove_none_from_dict(original: Mapping[str, Optional[Any]]) -> Dict[str, Any]: + new: Dict[str, Any] = {} + for key, value in original.items(): + if value is not None: + new[key] = value + return new diff --git a/skyflow/generated/rest/core/request_options.py b/skyflow/generated/rest/core/request_options.py new file mode 100644 index 00000000..1b388044 --- /dev/null +++ b/skyflow/generated/rest/core/request_options.py @@ -0,0 +1,35 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +try: + from typing import NotRequired # type: ignore +except ImportError: + from typing_extensions import NotRequired + + +class RequestOptions(typing.TypedDict, total=False): + """ + Additional options for request-specific configuration when calling APIs via the SDK. + This is used primarily as an optional final parameter for service functions. + + Attributes: + - timeout_in_seconds: int. The number of seconds to await an API call before timing out. + + - max_retries: int. The max number of retries to attempt if the API call fails. + + - additional_headers: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's header dict + + - additional_query_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's query parameters dict + + - additional_body_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's body parameters dict + + - chunk_size: int. The size, in bytes, to process each chunk of data being streamed back within the response. This equates to leveraging `chunk_size` within `requests` or `httpx`, and is only leveraged for file downloads. + """ + + timeout_in_seconds: NotRequired[int] + max_retries: NotRequired[int] + additional_headers: NotRequired[typing.Dict[str, typing.Any]] + additional_query_parameters: NotRequired[typing.Dict[str, typing.Any]] + additional_body_parameters: NotRequired[typing.Dict[str, typing.Any]] + chunk_size: NotRequired[int] diff --git a/skyflow/generated/rest/core/serialization.py b/skyflow/generated/rest/core/serialization.py new file mode 100644 index 00000000..cb5dcbf9 --- /dev/null +++ b/skyflow/generated/rest/core/serialization.py @@ -0,0 +1,272 @@ +# This file was auto-generated by Fern from our API Definition. + +import collections +import inspect +import typing + +import typing_extensions + +import pydantic + + +class FieldMetadata: + """ + Metadata class used to annotate fields to provide additional information. + + Example: + class MyDict(TypedDict): + field: typing.Annotated[str, FieldMetadata(alias="field_name")] + + Will serialize: `{"field": "value"}` + To: `{"field_name": "value"}` + """ + + alias: str + + def __init__(self, *, alias: str) -> None: + self.alias = alias + + +def convert_and_respect_annotation_metadata( + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, + direction: typing.Literal["read", "write"], +) -> typing.Any: + """ + Respect the metadata annotations on a field, such as aliasing. This function effectively + manipulates the dict-form of an object to respect the metadata annotations. This is primarily used for + TypedDicts, which cannot support aliasing out of the box, and can be extended for additional + utilities, such as defaults. + + Parameters + ---------- + object_ : typing.Any + + annotation : type + The type we're looking to apply typing annotations from + + inner_type : typing.Optional[type] + + Returns + ------- + typing.Any + """ + + if object_ is None: + return None + if inner_type is None: + inner_type = annotation + + clean_type = _remove_annotations(inner_type) + # Pydantic models + if ( + inspect.isclass(clean_type) + and issubclass(clean_type, pydantic.BaseModel) + and isinstance(object_, typing.Mapping) + ): + return _convert_mapping(object_, clean_type, direction) + # TypedDicts + if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + return _convert_mapping(object_, clean_type, direction) + + if ( + typing_extensions.get_origin(clean_type) == typing.Dict + or typing_extensions.get_origin(clean_type) == dict + or clean_type == typing.Dict + ) and isinstance(object_, typing.Dict): + key_type = typing_extensions.get_args(clean_type)[0] + value_type = typing_extensions.get_args(clean_type)[1] + + return { + key: convert_and_respect_annotation_metadata( + object_=value, + annotation=annotation, + inner_type=value_type, + direction=direction, + ) + for key, value in object_.items() + } + + # If you're iterating on a string, do not bother to coerce it to a sequence. + if not isinstance(object_, str): + if ( + typing_extensions.get_origin(clean_type) == typing.Set + or typing_extensions.get_origin(clean_type) == set + or clean_type == typing.Set + ) and isinstance(object_, typing.Set): + inner_type = typing_extensions.get_args(clean_type)[0] + return { + convert_and_respect_annotation_metadata( + object_=item, + annotation=annotation, + inner_type=inner_type, + direction=direction, + ) + for item in object_ + } + elif ( + ( + typing_extensions.get_origin(clean_type) == typing.List + or typing_extensions.get_origin(clean_type) == list + or clean_type == typing.List + ) + and isinstance(object_, typing.List) + ) or ( + ( + typing_extensions.get_origin(clean_type) == typing.Sequence + or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or clean_type == typing.Sequence + ) + and isinstance(object_, typing.Sequence) + ): + inner_type = typing_extensions.get_args(clean_type)[0] + return [ + convert_and_respect_annotation_metadata( + object_=item, + annotation=annotation, + inner_type=inner_type, + direction=direction, + ) + for item in object_ + ] + + if typing_extensions.get_origin(clean_type) == typing.Union: + # We should be able to ~relatively~ safely try to convert keys against all + # member types in the union, the edge case here is if one member aliases a field + # of the same name to a different name from another member + # Or if another member aliases a field of the same name that another member does not. + for member in typing_extensions.get_args(clean_type): + object_ = convert_and_respect_annotation_metadata( + object_=object_, + annotation=annotation, + inner_type=member, + direction=direction, + ) + return object_ + + annotated_type = _get_annotation(annotation) + if annotated_type is None: + return object_ + + # If the object is not a TypedDict, a Union, or other container (list, set, sequence, etc.) + # Then we can safely call it on the recursive conversion. + return object_ + + +def _convert_mapping( + object_: typing.Mapping[str, object], + expected_type: typing.Any, + direction: typing.Literal["read", "write"], +) -> typing.Mapping[str, object]: + converted_object: typing.Dict[str, object] = {} + annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) + aliases_to_field_names = _get_alias_to_field_name(annotations) + for key, value in object_.items(): + if direction == "read" and key in aliases_to_field_names: + dealiased_key = aliases_to_field_names.get(key) + if dealiased_key is not None: + type_ = annotations.get(dealiased_key) + else: + type_ = annotations.get(key) + # Note you can't get the annotation by the field name if you're in read mode, so you must check the aliases map + # + # So this is effectively saying if we're in write mode, and we don't have a type, or if we're in read mode and we don't have an alias + # then we can just pass the value through as is + if type_ is None: + converted_object[key] = value + elif direction == "read" and key not in aliases_to_field_names: + converted_object[key] = convert_and_respect_annotation_metadata( + object_=value, annotation=type_, direction=direction + ) + else: + converted_object[_alias_key(key, type_, direction, aliases_to_field_names)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_, direction=direction) + ) + return converted_object + + +def _get_annotation(type_: typing.Any) -> typing.Optional[typing.Any]: + maybe_annotated_type = typing_extensions.get_origin(type_) + if maybe_annotated_type is None: + return None + + if maybe_annotated_type == typing_extensions.NotRequired: + type_ = typing_extensions.get_args(type_)[0] + maybe_annotated_type = typing_extensions.get_origin(type_) + + if maybe_annotated_type == typing_extensions.Annotated: + return type_ + + return None + + +def _remove_annotations(type_: typing.Any) -> typing.Any: + maybe_annotated_type = typing_extensions.get_origin(type_) + if maybe_annotated_type is None: + return type_ + + if maybe_annotated_type == typing_extensions.NotRequired: + return _remove_annotations(typing_extensions.get_args(type_)[0]) + + if maybe_annotated_type == typing_extensions.Annotated: + return _remove_annotations(typing_extensions.get_args(type_)[0]) + + return type_ + + +def get_alias_to_field_mapping(type_: typing.Any) -> typing.Dict[str, str]: + annotations = typing_extensions.get_type_hints(type_, include_extras=True) + return _get_alias_to_field_name(annotations) + + +def get_field_to_alias_mapping(type_: typing.Any) -> typing.Dict[str, str]: + annotations = typing_extensions.get_type_hints(type_, include_extras=True) + return _get_field_to_alias_name(annotations) + + +def _get_alias_to_field_name( + field_to_hint: typing.Dict[str, typing.Any], +) -> typing.Dict[str, str]: + aliases = {} + for field, hint in field_to_hint.items(): + maybe_alias = _get_alias_from_type(hint) + if maybe_alias is not None: + aliases[maybe_alias] = field + return aliases + + +def _get_field_to_alias_name( + field_to_hint: typing.Dict[str, typing.Any], +) -> typing.Dict[str, str]: + aliases = {} + for field, hint in field_to_hint.items(): + maybe_alias = _get_alias_from_type(hint) + if maybe_alias is not None: + aliases[field] = maybe_alias + return aliases + + +def _get_alias_from_type(type_: typing.Any) -> typing.Optional[str]: + maybe_annotated_type = _get_annotation(type_) + + if maybe_annotated_type is not None: + # The actual annotations are 1 onward, the first is the annotated type + annotations = typing_extensions.get_args(maybe_annotated_type)[1:] + + for annotation in annotations: + if isinstance(annotation, FieldMetadata) and annotation.alias is not None: + return annotation.alias + return None + + +def _alias_key( + key: str, + type_: typing.Any, + direction: typing.Literal["read", "write"], + aliases_to_field_names: typing.Dict[str, str], +) -> str: + if direction == "read": + return aliases_to_field_names.get(key, key) + return _get_alias_from_type(type_=type_) or key diff --git a/skyflow/generated/rest/environment.py b/skyflow/generated/rest/environment.py new file mode 100644 index 00000000..8c4747ca --- /dev/null +++ b/skyflow/generated/rest/environment.py @@ -0,0 +1,8 @@ +# This file was auto-generated by Fern from our API Definition. + +import enum + + +class SkyflowEnvironment(enum.Enum): + PRODUCTION = "https://identifier.vault.skyflowapis.com" + SANDBOX = "https://identifier.vault.skyflowapis-preview.com" diff --git a/skyflow/generated/rest/errors/__init__.py b/skyflow/generated/rest/errors/__init__.py new file mode 100644 index 00000000..64f898f5 --- /dev/null +++ b/skyflow/generated/rest/errors/__init__.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +from .bad_request_error import BadRequestError +from .not_found_error import NotFoundError +from .unauthorized_error import UnauthorizedError + +__all__ = ["BadRequestError", "NotFoundError", "UnauthorizedError"] diff --git a/skyflow/generated/rest/errors/bad_request_error.py b/skyflow/generated/rest/errors/bad_request_error.py new file mode 100644 index 00000000..2f3dba61 --- /dev/null +++ b/skyflow/generated/rest/errors/bad_request_error.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.api_error import ApiError +import typing + + +class BadRequestError(ApiError): + def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): + super().__init__(status_code=400, body=body) diff --git a/skyflow/generated/rest/errors/not_found_error.py b/skyflow/generated/rest/errors/not_found_error.py new file mode 100644 index 00000000..b557be0a --- /dev/null +++ b/skyflow/generated/rest/errors/not_found_error.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.api_error import ApiError +import typing + + +class NotFoundError(ApiError): + def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): + super().__init__(status_code=404, body=body) diff --git a/skyflow/generated/rest/errors/unauthorized_error.py b/skyflow/generated/rest/errors/unauthorized_error.py new file mode 100644 index 00000000..6d01cc9f --- /dev/null +++ b/skyflow/generated/rest/errors/unauthorized_error.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.api_error import ApiError +import typing + + +class UnauthorizedError(ApiError): + def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): + super().__init__(status_code=401, body=body) diff --git a/skyflow/generated/rest/exceptions.py b/skyflow/generated/rest/exceptions.py deleted file mode 100644 index ef323e2e..00000000 --- a/skyflow/generated/rest/exceptions.py +++ /dev/null @@ -1,200 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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/skyflow/generated/rest/models/__init__.py b/skyflow/generated/rest/models/__init__.py deleted file mode 100644 index 379cf733..00000000 --- a/skyflow/generated/rest/models/__init__.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -# import models into model package -from skyflow.generated.rest.models.audit_event_audit_resource_type import AuditEventAuditResourceType -from skyflow.generated.rest.models.audit_event_context import AuditEventContext -from skyflow.generated.rest.models.audit_event_data import AuditEventData -from skyflow.generated.rest.models.audit_event_http_info import AuditEventHTTPInfo -from skyflow.generated.rest.models.batch_record_method import BatchRecordMethod -from skyflow.generated.rest.models.context_access_type import ContextAccessType -from skyflow.generated.rest.models.context_auth_mode import ContextAuthMode -from skyflow.generated.rest.models.detokenize_record_response_value_type import DetokenizeRecordResponseValueType -from skyflow.generated.rest.models.googlerpc_status import GooglerpcStatus -from skyflow.generated.rest.models.protobuf_any import ProtobufAny -from skyflow.generated.rest.models.query_service_execute_query_body import QueryServiceExecuteQueryBody -from skyflow.generated.rest.models.record_service_batch_operation_body import RecordServiceBatchOperationBody -from skyflow.generated.rest.models.record_service_bulk_delete_record_body import RecordServiceBulkDeleteRecordBody -from skyflow.generated.rest.models.record_service_insert_record_body import RecordServiceInsertRecordBody -from skyflow.generated.rest.models.record_service_update_record_body import RecordServiceUpdateRecordBody -from skyflow.generated.rest.models.redaction_enum_redaction import RedactionEnumREDACTION -from skyflow.generated.rest.models.request_action_type import RequestActionType -from skyflow.generated.rest.models.v1_audit_after_options import V1AuditAfterOptions -from skyflow.generated.rest.models.v1_audit_event_response import V1AuditEventResponse -from skyflow.generated.rest.models.v1_audit_response import V1AuditResponse -from skyflow.generated.rest.models.v1_audit_response_event import V1AuditResponseEvent -from skyflow.generated.rest.models.v1_audit_response_event_request import V1AuditResponseEventRequest -from skyflow.generated.rest.models.v1_bin_list_request import V1BINListRequest -from skyflow.generated.rest.models.v1_bin_list_response import V1BINListResponse -from skyflow.generated.rest.models.v1_byot import V1BYOT -from skyflow.generated.rest.models.v1_batch_operation_response import V1BatchOperationResponse -from skyflow.generated.rest.models.v1_batch_record import V1BatchRecord -from skyflow.generated.rest.models.v1_bulk_delete_record_response import V1BulkDeleteRecordResponse -from skyflow.generated.rest.models.v1_bulk_get_record_response import V1BulkGetRecordResponse -from skyflow.generated.rest.models.v1_card import V1Card -from skyflow.generated.rest.models.v1_delete_file_response import V1DeleteFileResponse -from skyflow.generated.rest.models.v1_delete_record_response import V1DeleteRecordResponse -from skyflow.generated.rest.models.v1_detokenize_payload import V1DetokenizePayload -from skyflow.generated.rest.models.v1_detokenize_record_request import V1DetokenizeRecordRequest -from skyflow.generated.rest.models.v1_detokenize_record_response import V1DetokenizeRecordResponse -from skyflow.generated.rest.models.v1_detokenize_response import V1DetokenizeResponse -from skyflow.generated.rest.models.v1_field_records import V1FieldRecords -from skyflow.generated.rest.models.v1_file_av_scan_status import V1FileAVScanStatus -from skyflow.generated.rest.models.v1_get_file_scan_status_response import V1GetFileScanStatusResponse -from skyflow.generated.rest.models.v1_get_query_response import V1GetQueryResponse -from skyflow.generated.rest.models.v1_insert_record_response import V1InsertRecordResponse -from skyflow.generated.rest.models.v1_member_type import V1MemberType -from skyflow.generated.rest.models.v1_record_meta_properties import V1RecordMetaProperties -from skyflow.generated.rest.models.v1_tokenize_payload import V1TokenizePayload -from skyflow.generated.rest.models.v1_tokenize_record_request import V1TokenizeRecordRequest -from skyflow.generated.rest.models.v1_tokenize_record_response import V1TokenizeRecordResponse -from skyflow.generated.rest.models.v1_tokenize_response import V1TokenizeResponse -from skyflow.generated.rest.models.v1_update_record_response import V1UpdateRecordResponse -from skyflow.generated.rest.models.v1_vault_field_mapping import V1VaultFieldMapping -from skyflow.generated.rest.models.v1_vault_schema_config import V1VaultSchemaConfig - -from skyflow.generated.rest.models.v1_get_auth_token_request import V1GetAuthTokenRequest -from skyflow.generated.rest.models.v1_get_auth_token_response import V1GetAuthTokenResponse \ No newline at end of file diff --git a/skyflow/generated/rest/models/audit_event_audit_resource_type.py b/skyflow/generated/rest/models/audit_event_audit_resource_type.py deleted file mode 100644 index c425dce7..00000000 --- a/skyflow/generated/rest/models/audit_event_audit_resource_type.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 AuditEventAuditResourceType(str, Enum): - """ - Type of the resource. - """ - - """ - allowed enum values - """ - NONE_API = 'NONE_API' - ACCOUNT = 'ACCOUNT' - AUDIT = 'AUDIT' - BASE_DATA_TYPE = 'BASE_DATA_TYPE' - FIELD_TEMPLATE = 'FIELD_TEMPLATE' - FILE = 'FILE' - KEY = 'KEY' - POLICY = 'POLICY' - PROTO_PARSE = 'PROTO_PARSE' - RECORD = 'RECORD' - ROLE = 'ROLE' - RULE = 'RULE' - SECRET = 'SECRET' - SERVICE_ACCOUNT = 'SERVICE_ACCOUNT' - TOKEN = 'TOKEN' - USER = 'USER' - VAULT = 'VAULT' - VAULT_TEMPLATE = 'VAULT_TEMPLATE' - WORKSPACE = 'WORKSPACE' - TABLE = 'TABLE' - POLICY_TEMPLATE = 'POLICY_TEMPLATE' - MEMBER = 'MEMBER' - TAG = 'TAG' - CONNECTION = 'CONNECTION' - MIGRATION = 'MIGRATION' - SCHEDULED_JOB = 'SCHEDULED_JOB' - JOB = 'JOB' - COLUMN_NAME = 'COLUMN_NAME' - NETWORK_TOKEN = 'NETWORK_TOKEN' - SUBSCRIPTION = 'SUBSCRIPTION' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of AuditEventAuditResourceType from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/audit_event_context.py b/skyflow/generated/rest/models/audit_event_context.py deleted file mode 100644 index af280eb0..00000000 --- a/skyflow/generated/rest/models/audit_event_context.py +++ /dev/null @@ -1,113 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.context_access_type import ContextAccessType -from skyflow.generated.rest.models.context_auth_mode import ContextAuthMode -from skyflow.generated.rest.models.v1_member_type import V1MemberType -from typing import Optional, Set -from typing_extensions import Self - -class AuditEventContext(BaseModel): - """ - Context for an audit event. - """ # noqa: E501 - change_id: Optional[StrictStr] = Field(default=None, description="ID for the audit event.", alias="changeID") - request_id: Optional[StrictStr] = Field(default=None, description="ID for the request that caused the event.", alias="requestID") - trace_id: Optional[StrictStr] = Field(default=None, description="ID for the request set by the service that received the request.", alias="traceID") - session_id: Optional[StrictStr] = Field(default=None, description="ID for the session in which the request was sent.", alias="sessionID") - actor: Optional[StrictStr] = Field(default=None, description="Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID.") - actor_type: Optional[V1MemberType] = Field(default=V1MemberType.NONE, alias="actorType") - access_type: Optional[ContextAccessType] = Field(default=ContextAccessType.ACCESS_NONE, alias="accessType") - ip_address: Optional[StrictStr] = Field(default=None, description="IP Address of the client that made the request.", alias="ipAddress") - origin: Optional[StrictStr] = Field(default=None, description="HTTP Origin request header (including scheme, hostname, and port) of the request.") - auth_mode: Optional[ContextAuthMode] = Field(default=ContextAuthMode.AUTH_NONE, alias="authMode") - jwt_id: Optional[StrictStr] = Field(default=None, description="ID of the JWT token.", alias="jwtID") - bearer_token_context_id: Optional[StrictStr] = Field(default=None, description="Embedded User Context.", alias="bearerTokenContextID") - __properties: ClassVar[List[str]] = ["changeID", "requestID", "traceID", "sessionID", "actor", "actorType", "accessType", "ipAddress", "origin", "authMode", "jwtID", "bearerTokenContextID"] - - 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 AuditEventContext 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 AuditEventContext from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "changeID": obj.get("changeID"), - "requestID": obj.get("requestID"), - "traceID": obj.get("traceID"), - "sessionID": obj.get("sessionID"), - "actor": obj.get("actor"), - "actorType": obj.get("actorType") if obj.get("actorType") is not None else V1MemberType.NONE, - "accessType": obj.get("accessType") if obj.get("accessType") is not None else ContextAccessType.ACCESS_NONE, - "ipAddress": obj.get("ipAddress"), - "origin": obj.get("origin"), - "authMode": obj.get("authMode") if obj.get("authMode") is not None else ContextAuthMode.AUTH_NONE, - "jwtID": obj.get("jwtID"), - "bearerTokenContextID": obj.get("bearerTokenContextID") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/audit_event_data.py b/skyflow/generated/rest/models/audit_event_data.py deleted file mode 100644 index 5a463f00..00000000 --- a/skyflow/generated/rest/models/audit_event_data.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class AuditEventData(BaseModel): - """ - Any Sensitive data that needs to be wrapped. - """ # noqa: E501 - content: Optional[StrictStr] = Field(default=None, description="The entire body of the data requested or the query fired.") - __properties: ClassVar[List[str]] = ["content"] - - 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 AuditEventData 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 AuditEventData from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "content": obj.get("content") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/audit_event_http_info.py b/skyflow/generated/rest/models/audit_event_http_info.py deleted file mode 100644 index b3b2f074..00000000 --- a/skyflow/generated/rest/models/audit_event_http_info.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class AuditEventHTTPInfo(BaseModel): - """ - AuditEventHTTPInfo - """ # noqa: E501 - uri: Optional[StrictStr] = Field(default=None, description="The http URI that is used.", alias="URI") - method: Optional[StrictStr] = Field(default=None, description="http method used.") - __properties: ClassVar[List[str]] = ["URI", "method"] - - 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 AuditEventHTTPInfo 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 AuditEventHTTPInfo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "URI": obj.get("URI"), - "method": obj.get("method") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/batch_record_method.py b/skyflow/generated/rest/models/batch_record_method.py deleted file mode 100644 index a2892049..00000000 --- a/skyflow/generated/rest/models/batch_record_method.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 BatchRecordMethod(str, Enum): - """ - Method of the operation. - """ - - """ - allowed enum values - """ - NONE = 'NONE' - POST = 'POST' - PUT = 'PUT' - GET = 'GET' - DELETE = 'DELETE' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of BatchRecordMethod from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/context_access_type.py b/skyflow/generated/rest/models/context_access_type.py deleted file mode 100644 index e00a9df9..00000000 --- a/skyflow/generated/rest/models/context_access_type.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 ContextAccessType(str, Enum): - """ - Type of access for the request. - """ - - """ - allowed enum values - """ - ACCESS_NONE = 'ACCESS_NONE' - API = 'API' - SQL = 'SQL' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of ContextAccessType from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/context_auth_mode.py b/skyflow/generated/rest/models/context_auth_mode.py deleted file mode 100644 index fb803e7a..00000000 --- a/skyflow/generated/rest/models/context_auth_mode.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 ContextAuthMode(str, Enum): - """ - Authentication mode the `actor` used. - """ - - """ - allowed enum values - """ - AUTH_NONE = 'AUTH_NONE' - OKTA_JWT = 'OKTA_JWT' - SERVICE_ACCOUNT_JWT = 'SERVICE_ACCOUNT_JWT' - PAT_JWT = 'PAT_JWT' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of ContextAuthMode from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/detokenize_record_response_value_type.py b/skyflow/generated/rest/models/detokenize_record_response_value_type.py deleted file mode 100644 index 62460141..00000000 --- a/skyflow/generated/rest/models/detokenize_record_response_value_type.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 DetokenizeRecordResponseValueType(str, Enum): - """ - DetokenizeRecordResponseValueType - """ - - """ - allowed enum values - """ - NONE = 'NONE' - STRING = 'STRING' - INTEGER = 'INTEGER' - FLOAT = 'FLOAT' - BOOL = 'BOOL' - DATETIME = 'DATETIME' - JSON = 'JSON' - ARRAY = 'ARRAY' - DATE = 'DATE' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of DetokenizeRecordResponseValueType from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/googlerpc_status.py b/skyflow/generated/rest/models/googlerpc_status.py deleted file mode 100644 index b9914c58..00000000 --- a/skyflow/generated/rest/models/googlerpc_status.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictInt, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.protobuf_any import ProtobufAny -from typing import Optional, Set -from typing_extensions import Self - -class GooglerpcStatus(BaseModel): - """ - GooglerpcStatus - """ # noqa: E501 - code: Optional[StrictInt] = None - message: Optional[StrictStr] = None - details: Optional[List[ProtobufAny]] = None - __properties: ClassVar[List[str]] = ["code", "message", "details"] - - 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 GooglerpcStatus 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 details (list) - _items = [] - if self.details: - for _item_details in self.details: - if _item_details: - _items.append(_item_details.to_dict()) - _dict['details'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of GooglerpcStatus from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "code": obj.get("code"), - "message": obj.get("message"), - "details": [ProtobufAny.from_dict(_item) for _item in obj["details"]] if obj.get("details") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/protobuf_any.py b/skyflow/generated/rest/models/protobuf_any.py deleted file mode 100644 index e29a6356..00000000 --- a/skyflow/generated/rest/models/protobuf_any.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class ProtobufAny(BaseModel): - """ - ProtobufAny - """ # noqa: E501 - type: Optional[StrictStr] = Field(default=None, alias="@type") - additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["@type"] - - 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 ProtobufAny 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 ProtobufAny 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") - }) - # 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 - - diff --git a/skyflow/generated/rest/models/query_service_execute_query_body.py b/skyflow/generated/rest/models/query_service_execute_query_body.py deleted file mode 100644 index fa6a9bf9..00000000 --- a/skyflow/generated/rest/models/query_service_execute_query_body.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class QueryServiceExecuteQueryBody(BaseModel): - """ - QueryServiceExecuteQueryBody - """ # noqa: E501 - query: Optional[StrictStr] = Field(default=None, description="The SQL query to execute.

Supported commands:
  • SELECT
Supported operators:
  • >
  • <
  • =
  • AND
  • OR
  • NOT
  • LIKE
  • ILIKE
  • NULL
  • NOT NULL
Supported keywords:
  • FROM
  • JOIN
  • INNER JOIN
  • LEFT OUTER JOIN
  • LEFT JOIN
  • RIGHT OUTER JOIN
  • RIGHT JOIN
  • FULL OUTER JOIN
  • FULL JOIN
  • OFFSET
  • LIMIT
  • WHERE
Supported functions:
  • AVG()
  • SUM()
  • COUNT()
  • MIN()
  • MAX()
  • REDACTION()
") - __properties: ClassVar[List[str]] = ["query"] - - 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 QueryServiceExecuteQueryBody 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 QueryServiceExecuteQueryBody from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "query": obj.get("query") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/record_service_batch_operation_body.py b/skyflow/generated/rest/models/record_service_batch_operation_body.py deleted file mode 100644 index fe6ef37e..00000000 --- a/skyflow/generated/rest/models/record_service_batch_operation_body.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictBool -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_batch_record import V1BatchRecord -from skyflow.generated.rest.models.v1_byot import V1BYOT -from typing import Optional, Set -from typing_extensions import Self - -class RecordServiceBatchOperationBody(BaseModel): - """ - RecordServiceBatchOperationBody - """ # noqa: E501 - records: Optional[List[V1BatchRecord]] = Field(default=None, description="Record operations to perform.") - continue_on_error: Optional[StrictBool] = Field(default=None, description="Continue performing operations on partial errors.", alias="continueOnError") - byot: Optional[V1BYOT] = V1BYOT.DISABLE - __properties: ClassVar[List[str]] = ["records", "continueOnError", "byot"] - - 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 RecordServiceBatchOperationBody 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 records (list) - _items = [] - if self.records: - for _item_records in self.records: - if _item_records: - _items.append(_item_records.to_dict()) - _dict['records'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of RecordServiceBatchOperationBody from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "records": [V1BatchRecord.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None, - "continueOnError": obj.get("continueOnError"), - "byot": obj.get("byot") if obj.get("byot") is not None else V1BYOT.DISABLE - }) - return _obj - - diff --git a/skyflow/generated/rest/models/record_service_bulk_delete_record_body.py b/skyflow/generated/rest/models/record_service_bulk_delete_record_body.py deleted file mode 100644 index b12f79a8..00000000 --- a/skyflow/generated/rest/models/record_service_bulk_delete_record_body.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class RecordServiceBulkDeleteRecordBody(BaseModel): - """ - RecordServiceBulkDeleteRecordBody - """ # noqa: E501 - skyflow_ids: Optional[List[StrictStr]] = Field(default=None, description="`skyflow_id` values of the records to delete. If `*` is specified, this operation deletes all records in the table.") - __properties: ClassVar[List[str]] = ["skyflow_ids"] - - 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 RecordServiceBulkDeleteRecordBody 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 RecordServiceBulkDeleteRecordBody from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skyflow_ids": obj.get("skyflow_ids") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/record_service_insert_record_body.py b/skyflow/generated/rest/models/record_service_insert_record_body.py deleted file mode 100644 index c067fe25..00000000 --- a/skyflow/generated/rest/models/record_service_insert_record_body.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictBool, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_byot import V1BYOT -from skyflow.generated.rest.models.v1_field_records import V1FieldRecords -from typing import Optional, Set -from typing_extensions import Self - -class RecordServiceInsertRecordBody(BaseModel): - """ - RecordServiceInsertRecordBody - """ # noqa: E501 - records: Optional[List[V1FieldRecords]] = Field(default=None, description="Record values and tokens.") - tokenization: Optional[StrictBool] = Field(default=None, description="If `true`, this operation returns tokens for fields with tokenization enabled.") - upsert: Optional[StrictStr] = Field(default=None, description="Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.

When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.") - homogeneous: Optional[StrictBool] = Field(default=False, description="If `true`, this operation mandates that all the records have the same fields. This parameter does not work with upsert.") - byot: Optional[V1BYOT] = V1BYOT.DISABLE - __properties: ClassVar[List[str]] = ["records", "tokenization", "upsert", "homogeneous", "byot"] - - 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 RecordServiceInsertRecordBody 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 records (list) - _items = [] - if self.records: - for _item_records in self.records: - if _item_records: - _items.append(_item_records.to_dict()) - _dict['records'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of RecordServiceInsertRecordBody from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "records": [V1FieldRecords.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None, - "tokenization": obj.get("tokenization"), - "upsert": obj.get("upsert"), - "homogeneous": obj.get("homogeneous") if obj.get("homogeneous") is not None else False, - "byot": obj.get("byot") if obj.get("byot") is not None else V1BYOT.DISABLE - }) - return _obj - - diff --git a/skyflow/generated/rest/models/record_service_update_record_body.py b/skyflow/generated/rest/models/record_service_update_record_body.py deleted file mode 100644 index 627a2f6e..00000000 --- a/skyflow/generated/rest/models/record_service_update_record_body.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictBool -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_byot import V1BYOT -from skyflow.generated.rest.models.v1_field_records import V1FieldRecords -from typing import Optional, Set -from typing_extensions import Self - -class RecordServiceUpdateRecordBody(BaseModel): - """ - RecordServiceUpdateRecordBody - """ # noqa: E501 - record: Optional[V1FieldRecords] = None - tokenization: Optional[StrictBool] = Field(default=None, description="If `true`, this operation returns tokens for fields with tokenization enabled.") - byot: Optional[V1BYOT] = V1BYOT.DISABLE - __properties: ClassVar[List[str]] = ["record", "tokenization", "byot"] - - 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 RecordServiceUpdateRecordBody 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 - if self.record: - _dict['record'] = self.record.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of RecordServiceUpdateRecordBody from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "record": V1FieldRecords.from_dict(obj["record"]) if obj.get("record") is not None else None, - "tokenization": obj.get("tokenization"), - "byot": obj.get("byot") if obj.get("byot") is not None else V1BYOT.DISABLE - }) - return _obj - - diff --git a/skyflow/generated/rest/models/redaction_enum_redaction.py b/skyflow/generated/rest/models/redaction_enum_redaction.py deleted file mode 100644 index 82f1a16e..00000000 --- a/skyflow/generated/rest/models/redaction_enum_redaction.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 RedactionEnumREDACTION(str, Enum): - """ - Redaction type. Subject to policies assigned to the API caller. When used for detokenization, only supported for vaults that support [column groups](/tokenization-column-groups/). - """ - - """ - allowed enum values - """ - DEFAULT = 'DEFAULT' - REDACTED = 'REDACTED' - MASKED = 'MASKED' - PLAIN_TEXT = 'PLAIN_TEXT' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of RedactionEnumREDACTION from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/request_action_type.py b/skyflow/generated/rest/models/request_action_type.py deleted file mode 100644 index 2137d2eb..00000000 --- a/skyflow/generated/rest/models/request_action_type.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 RequestActionType(str, Enum): - """ - RequestActionType - """ - - """ - allowed enum values - """ - NONE = 'NONE' - ASSIGN = 'ASSIGN' - CREATE = 'CREATE' - DELETE = 'DELETE' - EXECUTE = 'EXECUTE' - LIST = 'LIST' - READ = 'READ' - UNASSIGN = 'UNASSIGN' - UPDATE = 'UPDATE' - VALIDATE = 'VALIDATE' - LOGIN = 'LOGIN' - ROTATE = 'ROTATE' - SCHEDULEROTATION = 'SCHEDULEROTATION' - SCHEDULEROTATIONALERT = 'SCHEDULEROTATIONALERT' - IMPORT = 'IMPORT' - GETIMPORTPARAMETERS = 'GETIMPORTPARAMETERS' - PING = 'PING' - GETCLOUDPROVIDER = 'GETCLOUDPROVIDER' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of RequestActionType from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/v1_audit_after_options.py b/skyflow/generated/rest/models/v1_audit_after_options.py deleted file mode 100644 index f8c441ef..00000000 --- a/skyflow/generated/rest/models/v1_audit_after_options.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1AuditAfterOptions(BaseModel): - """ - V1AuditAfterOptions - """ # noqa: E501 - timestamp: Optional[StrictStr] = Field(default=None, description="Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.") - change_id: Optional[StrictStr] = Field(default=None, description="Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank.", alias="changeID") - __properties: ClassVar[List[str]] = ["timestamp", "changeID"] - - 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 V1AuditAfterOptions 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 V1AuditAfterOptions from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "timestamp": obj.get("timestamp"), - "changeID": obj.get("changeID") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_audit_event_response.py b/skyflow/generated/rest/models/v1_audit_event_response.py deleted file mode 100644 index bb78dfc8..00000000 --- a/skyflow/generated/rest/models/v1_audit_event_response.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictInt, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.audit_event_data import AuditEventData -from typing import Optional, Set -from typing_extensions import Self - -class V1AuditEventResponse(BaseModel): - """ - Contains fields for defining Response Properties. - """ # noqa: E501 - code: Optional[StrictInt] = Field(default=None, description="The status of the overall operation.") - message: Optional[StrictStr] = Field(default=None, description="The status message for the overall operation.") - data: Optional[AuditEventData] = None - timestamp: Optional[StrictStr] = Field(default=None, description="time when this response is generated, use extention method to set it.") - __properties: ClassVar[List[str]] = ["code", "message", "data", "timestamp"] - - 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 V1AuditEventResponse 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 data - if self.data: - _dict['data'] = self.data.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1AuditEventResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "code": obj.get("code"), - "message": obj.get("message"), - "data": AuditEventData.from_dict(obj["data"]) if obj.get("data") is not None else None, - "timestamp": obj.get("timestamp") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_audit_response.py b/skyflow/generated/rest/models/v1_audit_response.py deleted file mode 100644 index 06a3d0df..00000000 --- a/skyflow/generated/rest/models/v1_audit_response.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_audit_after_options import V1AuditAfterOptions -from skyflow.generated.rest.models.v1_audit_response_event import V1AuditResponseEvent -from typing import Optional, Set -from typing_extensions import Self - -class V1AuditResponse(BaseModel): - """ - V1AuditResponse - """ # noqa: E501 - event: Optional[List[V1AuditResponseEvent]] = Field(default=None, description="Events matching the query.") - next_ops: Optional[V1AuditAfterOptions] = Field(default=None, alias="nextOps") - __properties: ClassVar[List[str]] = ["event", "nextOps"] - - 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 V1AuditResponse 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 event (list) - _items = [] - if self.event: - for _item_event in self.event: - if _item_event: - _items.append(_item_event.to_dict()) - _dict['event'] = _items - # override the default output from pydantic by calling `to_dict()` of next_ops - if self.next_ops: - _dict['nextOps'] = self.next_ops.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1AuditResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "event": [V1AuditResponseEvent.from_dict(_item) for _item in obj["event"]] if obj.get("event") is not None else None, - "nextOps": V1AuditAfterOptions.from_dict(obj["nextOps"]) if obj.get("nextOps") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_audit_response_event.py b/skyflow/generated/rest/models/v1_audit_response_event.py deleted file mode 100644 index 0edd2a52..00000000 --- a/skyflow/generated/rest/models/v1_audit_response_event.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.audit_event_context import AuditEventContext -from skyflow.generated.rest.models.v1_audit_event_response import V1AuditEventResponse -from skyflow.generated.rest.models.v1_audit_response_event_request import V1AuditResponseEventRequest -from typing import Optional, Set -from typing_extensions import Self - -class V1AuditResponseEvent(BaseModel): - """ - Audit event details. - """ # noqa: E501 - context: Optional[AuditEventContext] = None - request: Optional[V1AuditResponseEventRequest] = None - response: Optional[V1AuditEventResponse] = None - parent_account_id: Optional[StrictStr] = Field(default=None, description="Parent account ID of the account that made the request, if any.", alias="parentAccountID") - account_id: Optional[StrictStr] = Field(default=None, description="ID of the account that made the request.", alias="accountID") - resource_ids: Optional[List[StrictStr]] = Field(default=None, description="IDs for resources involved in the event. Presented in `{resourceType}/{resourceID}` format. For example, `VAULT/cd1d815aa09b4cbfbb803bd20349f202`.", alias="resourceIDs") - __properties: ClassVar[List[str]] = ["context", "request", "response", "parentAccountID", "accountID", "resourceIDs"] - - 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 V1AuditResponseEvent 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 context - if self.context: - _dict['context'] = self.context.to_dict() - # override the default output from pydantic by calling `to_dict()` of request - if self.request: - _dict['request'] = self.request.to_dict() - # override the default output from pydantic by calling `to_dict()` of response - if self.response: - _dict['response'] = self.response.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1AuditResponseEvent from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "context": AuditEventContext.from_dict(obj["context"]) if obj.get("context") is not None else None, - "request": V1AuditResponseEventRequest.from_dict(obj["request"]) if obj.get("request") is not None else None, - "response": V1AuditEventResponse.from_dict(obj["response"]) if obj.get("response") is not None else None, - "parentAccountID": obj.get("parentAccountID"), - "accountID": obj.get("accountID"), - "resourceIDs": obj.get("resourceIDs") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_audit_response_event_request.py b/skyflow/generated/rest/models/v1_audit_response_event_request.py deleted file mode 100644 index 2b4c6546..00000000 --- a/skyflow/generated/rest/models/v1_audit_response_event_request.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.audit_event_audit_resource_type import AuditEventAuditResourceType -from skyflow.generated.rest.models.audit_event_data import AuditEventData -from skyflow.generated.rest.models.audit_event_http_info import AuditEventHTTPInfo -from skyflow.generated.rest.models.request_action_type import RequestActionType -from typing import Optional, Set -from typing_extensions import Self - -class V1AuditResponseEventRequest(BaseModel): - """ - Contains fields for defining Request Properties. - """ # noqa: E501 - data: Optional[AuditEventData] = None - api_name: Optional[StrictStr] = Field(default=None, description="API name.", alias="apiName") - workspace_id: Optional[StrictStr] = Field(default=None, description="The workspaceID (if any) of the request.", alias="workspaceID") - vault_id: Optional[StrictStr] = Field(default=None, description="The vaultID (if any) of the request.", alias="vaultID") - tags: Optional[List[StrictStr]] = Field(default=None, description="Tags associated with the event. To provide better search capabilities. Like login.") - timestamp: Optional[StrictStr] = Field(default=None, description="time when this request is generated, use extention method to set it.") - action_type: Optional[RequestActionType] = Field(default=RequestActionType.NONE, alias="actionType") - resource_type: Optional[AuditEventAuditResourceType] = Field(default=AuditEventAuditResourceType.NONE_API, alias="resourceType") - http_info: Optional[AuditEventHTTPInfo] = Field(default=None, alias="httpInfo") - __properties: ClassVar[List[str]] = ["data", "apiName", "workspaceID", "vaultID", "tags", "timestamp", "actionType", "resourceType", "httpInfo"] - - 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 V1AuditResponseEventRequest 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 data - if self.data: - _dict['data'] = self.data.to_dict() - # override the default output from pydantic by calling `to_dict()` of http_info - if self.http_info: - _dict['httpInfo'] = self.http_info.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1AuditResponseEventRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "data": AuditEventData.from_dict(obj["data"]) if obj.get("data") is not None else None, - "apiName": obj.get("apiName"), - "workspaceID": obj.get("workspaceID"), - "vaultID": obj.get("vaultID"), - "tags": obj.get("tags"), - "timestamp": obj.get("timestamp"), - "actionType": obj.get("actionType") if obj.get("actionType") is not None else RequestActionType.NONE, - "resourceType": obj.get("resourceType") if obj.get("resourceType") is not None else AuditEventAuditResourceType.NONE_API, - "httpInfo": AuditEventHTTPInfo.from_dict(obj["httpInfo"]) if obj.get("httpInfo") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_batch_operation_response.py b/skyflow/generated/rest/models/v1_batch_operation_response.py deleted file mode 100644 index b790403f..00000000 --- a/skyflow/generated/rest/models/v1_batch_operation_response.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1BatchOperationResponse(BaseModel): - """ - V1BatchOperationResponse - """ # noqa: E501 - vault_id: Optional[StrictStr] = Field(default=None, description="ID of the vault.", alias="vaultID") - responses: Optional[List[Dict[str, Any]]] = Field(default=None, description="Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs:
  • `POST` returns an Insert Records response.
  • `PUT` returns an Update Record response.
  • `GET` returns a Get Record response.
  • `DELETE` returns a Delete Record response.
") - __properties: ClassVar[List[str]] = ["vaultID", "responses"] - - 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 V1BatchOperationResponse 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 V1BatchOperationResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "vaultID": obj.get("vaultID"), - "responses": obj.get("responses") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_batch_record.py b/skyflow/generated/rest/models/v1_batch_record.py deleted file mode 100644 index 76480a55..00000000 --- a/skyflow/generated/rest/models/v1_batch_record.py +++ /dev/null @@ -1,108 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictBool, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.batch_record_method import BatchRecordMethod -from skyflow.generated.rest.models.redaction_enum_redaction import RedactionEnumREDACTION -from typing import Optional, Set -from typing_extensions import Self - -class V1BatchRecord(BaseModel): - """ - V1BatchRecord - """ # noqa: E501 - fields: Optional[Dict[str, Any]] = Field(default=None, description="Field and value key pairs. For example, `{'field_1':'value_1', 'field_2':'value_2'}`. Only valid when `method` is `POST` or `PUT`.") - table_name: Optional[StrictStr] = Field(default=None, description="Name of the table to perform the operation on.", alias="tableName") - method: Optional[BatchRecordMethod] = BatchRecordMethod.NONE - batch_id: Optional[StrictStr] = Field(default=None, description="ID to group operations by. Operations in the same group are executed sequentially.", alias="batchID") - redaction: Optional[RedactionEnumREDACTION] = RedactionEnumREDACTION.DEFAULT - tokenization: Optional[StrictBool] = Field(default=None, description="If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified.") - id: Optional[StrictStr] = Field(default=None, description="`skyflow_id` for the record. Only valid when `method` is `GET`, `DELETE`, or `PUT`.", alias="ID") - download_url: Optional[StrictBool] = Field(default=None, description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.", alias="downloadURL") - upsert: Optional[StrictStr] = Field(default=None, description="Column that stores primary keys for upsert operations. The column must be marked as unique in the vault schema. Only valid when `method` is `POST`.") - tokens: Optional[Dict[str, Any]] = Field(default=None, description="Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`.") - __properties: ClassVar[List[str]] = ["fields", "tableName", "method", "batchID", "redaction", "tokenization", "ID", "downloadURL", "upsert", "tokens"] - - 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 V1BatchRecord 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 V1BatchRecord from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "fields": obj.get("fields"), - "tableName": obj.get("tableName"), - "method": obj.get("method") if obj.get("method") is not None else BatchRecordMethod.NONE, - "batchID": obj.get("batchID"), - "redaction": obj.get("redaction") if obj.get("redaction") is not None else RedactionEnumREDACTION.DEFAULT, - "tokenization": obj.get("tokenization"), - "ID": obj.get("ID"), - "downloadURL": obj.get("downloadURL"), - "upsert": obj.get("upsert"), - "tokens": obj.get("tokens") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_bin_list_request.py b/skyflow/generated/rest/models/v1_bin_list_request.py deleted file mode 100644 index 71de651e..00000000 --- a/skyflow/generated/rest/models/v1_bin_list_request.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_vault_schema_config import V1VaultSchemaConfig -from typing import Optional, Set -from typing_extensions import Self - -class V1BINListRequest(BaseModel): - """ - Request to return specific card metadata. - """ # noqa: E501 - fields: Optional[List[StrictStr]] = Field(default=None, description="Fields to return. If not specified, all fields are returned.") - bin: Optional[StrictStr] = Field(default=None, description="BIN of the card.", alias="BIN") - vault_schema_config: Optional[V1VaultSchemaConfig] = None - skyflow_id: Optional[StrictStr] = Field(default=None, description="skyflow_id of the record.") - __properties: ClassVar[List[str]] = ["fields", "BIN", "vault_schema_config", "skyflow_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 V1BINListRequest 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 vault_schema_config - if self.vault_schema_config: - _dict['vault_schema_config'] = self.vault_schema_config.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1BINListRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "fields": obj.get("fields"), - "BIN": obj.get("BIN"), - "vault_schema_config": V1VaultSchemaConfig.from_dict(obj["vault_schema_config"]) if obj.get("vault_schema_config") is not None else None, - "skyflow_id": obj.get("skyflow_id") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_bin_list_response.py b/skyflow/generated/rest/models/v1_bin_list_response.py deleted file mode 100644 index becf8bb4..00000000 --- a/skyflow/generated/rest/models/v1_bin_list_response.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_card import V1Card -from typing import Optional, Set -from typing_extensions import Self - -class V1BINListResponse(BaseModel): - """ - Response to the Get BIN request. - """ # noqa: E501 - cards_data: Optional[List[V1Card]] = Field(default=None, description="Card metadata associated with the specified BIN.") - __properties: ClassVar[List[str]] = ["cards_data"] - - 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 V1BINListResponse 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 cards_data (list) - _items = [] - if self.cards_data: - for _item_cards_data in self.cards_data: - if _item_cards_data: - _items.append(_item_cards_data.to_dict()) - _dict['cards_data'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1BINListResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "cards_data": [V1Card.from_dict(_item) for _item in obj["cards_data"]] if obj.get("cards_data") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_bulk_delete_record_response.py b/skyflow/generated/rest/models/v1_bulk_delete_record_response.py deleted file mode 100644 index 726e1c40..00000000 --- a/skyflow/generated/rest/models/v1_bulk_delete_record_response.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1BulkDeleteRecordResponse(BaseModel): - """ - V1BulkDeleteRecordResponse - """ # noqa: E501 - record_id_response: Optional[List[StrictStr]] = Field(default=None, description="IDs for the deleted records, or `*` if all records were deleted.", alias="RecordIDResponse") - __properties: ClassVar[List[str]] = ["RecordIDResponse"] - - 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 V1BulkDeleteRecordResponse 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 V1BulkDeleteRecordResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "RecordIDResponse": obj.get("RecordIDResponse") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_bulk_get_record_response.py b/skyflow/generated/rest/models/v1_bulk_get_record_response.py deleted file mode 100644 index df8095df..00000000 --- a/skyflow/generated/rest/models/v1_bulk_get_record_response.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_field_records import V1FieldRecords -from typing import Optional, Set -from typing_extensions import Self - -class V1BulkGetRecordResponse(BaseModel): - """ - V1BulkGetRecordResponse - """ # noqa: E501 - records: Optional[List[V1FieldRecords]] = Field(default=None, description="The specified records.") - __properties: ClassVar[List[str]] = ["records"] - - 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 V1BulkGetRecordResponse 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 records (list) - _items = [] - if self.records: - for _item_records in self.records: - if _item_records: - _items.append(_item_records.to_dict()) - _dict['records'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1BulkGetRecordResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "records": [V1FieldRecords.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_byot.py b/skyflow/generated/rest/models/v1_byot.py deleted file mode 100644 index 754a70dc..00000000 --- a/skyflow/generated/rest/models/v1_byot.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 V1BYOT(str, Enum): - """ - Token insertion behavior. - DISABLE: Tokens aren't allowed for any fields. If tokens are specified, the request fails. - ENABLE: Tokens are allowed—but not required—for all fields. If tokens are specified, they're inserted. - ENABLE_STRICT: Tokens are required for all fields. If tokens are specified, they're inserted. If not, the request fails. - """ - - """ - allowed enum values - """ - DISABLE = 'DISABLE' - ENABLE = 'ENABLE' - ENABLE_STRICT = 'ENABLE_STRICT' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of V1BYOT from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/v1_card.py b/skyflow/generated/rest/models/v1_card.py deleted file mode 100644 index 2245ee74..00000000 --- a/skyflow/generated/rest/models/v1_card.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1Card(BaseModel): - """ - Card metadata of the requested BIN. - """ # noqa: E501 - bin: Optional[StrictStr] = Field(default=None, description="BIN of the card.", alias="BIN") - issuer_name: Optional[StrictStr] = Field(default=None, description="Name of the card issuer bank.") - country_code: Optional[StrictStr] = Field(default=None, description="Country code of the card.") - currency: Optional[StrictStr] = Field(default=None, description="Currency of the card.") - card_type: Optional[StrictStr] = Field(default=None, description="Type of the card.") - card_category: Optional[StrictStr] = Field(default=None, description="Category of the card.") - card_scheme: Optional[StrictStr] = Field(default=None, description="Scheme of the card.") - card_last_four_digits: Optional[StrictStr] = Field(default=None, description="Last four digits of the card number.") - card_expiry: Optional[StrictStr] = Field(default=None, description="Expiry date of the card.") - __properties: ClassVar[List[str]] = ["BIN", "issuer_name", "country_code", "currency", "card_type", "card_category", "card_scheme", "card_last_four_digits", "card_expiry"] - - 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 V1Card 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 V1Card from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "BIN": obj.get("BIN"), - "issuer_name": obj.get("issuer_name"), - "country_code": obj.get("country_code"), - "currency": obj.get("currency"), - "card_type": obj.get("card_type"), - "card_category": obj.get("card_category"), - "card_scheme": obj.get("card_scheme"), - "card_last_four_digits": obj.get("card_last_four_digits"), - "card_expiry": obj.get("card_expiry") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_delete_file_response.py b/skyflow/generated/rest/models/v1_delete_file_response.py deleted file mode 100644 index e68030c0..00000000 --- a/skyflow/generated/rest/models/v1_delete_file_response.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictBool, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1DeleteFileResponse(BaseModel): - """ - V1DeleteFileResponse - """ # noqa: E501 - skyflow_id: Optional[StrictStr] = Field(default=None, description="ID of the record.") - deleted: Optional[StrictBool] = Field(default=None, description="If `true`, the file was deleted.") - __properties: ClassVar[List[str]] = ["skyflow_id", "deleted"] - - 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 V1DeleteFileResponse 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 V1DeleteFileResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skyflow_id": obj.get("skyflow_id"), - "deleted": obj.get("deleted") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_delete_record_response.py b/skyflow/generated/rest/models/v1_delete_record_response.py deleted file mode 100644 index a56d3ba2..00000000 --- a/skyflow/generated/rest/models/v1_delete_record_response.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictBool, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1DeleteRecordResponse(BaseModel): - """ - V1DeleteRecordResponse - """ # noqa: E501 - skyflow_id: Optional[StrictStr] = Field(default=None, description="ID of the deleted record.") - deleted: Optional[StrictBool] = Field(default=None, description="If `true`, the record was deleted.") - __properties: ClassVar[List[str]] = ["skyflow_id", "deleted"] - - 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 V1DeleteRecordResponse 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 V1DeleteRecordResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skyflow_id": obj.get("skyflow_id"), - "deleted": obj.get("deleted") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_detokenize_payload.py b/skyflow/generated/rest/models/v1_detokenize_payload.py deleted file mode 100644 index 0394aa1c..00000000 --- a/skyflow/generated/rest/models/v1_detokenize_payload.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictBool -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_detokenize_record_request import V1DetokenizeRecordRequest -from typing import Optional, Set -from typing_extensions import Self - -class V1DetokenizePayload(BaseModel): - """ - V1DetokenizePayload - """ # noqa: E501 - detokenization_parameters: Optional[List[V1DetokenizeRecordRequest]] = Field(default=None, description="Detokenization details.", alias="detokenizationParameters") - download_url: Optional[StrictBool] = Field(default=None, description="If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.", alias="downloadURL") - continue_on_error: Optional[StrictBool] = Field(default=False, description="If `true`, the detokenization request continues even if an error occurs.", alias="continueOnError") - __properties: ClassVar[List[str]] = ["detokenizationParameters", "downloadURL", "continueOnError"] - - 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 V1DetokenizePayload 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 detokenization_parameters (list) - _items = [] - if self.detokenization_parameters: - for _item_detokenization_parameters in self.detokenization_parameters: - if _item_detokenization_parameters: - _items.append(_item_detokenization_parameters.to_dict()) - _dict['detokenizationParameters'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1DetokenizePayload from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "detokenizationParameters": [V1DetokenizeRecordRequest.from_dict(_item) for _item in obj["detokenizationParameters"]] if obj.get("detokenizationParameters") is not None else None, - "downloadURL": obj.get("downloadURL"), - "continueOnError": obj.get("continueOnError") if obj.get("continueOnError") is not None else False - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_detokenize_record_request.py b/skyflow/generated/rest/models/v1_detokenize_record_request.py deleted file mode 100644 index 2899501b..00000000 --- a/skyflow/generated/rest/models/v1_detokenize_record_request.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.redaction_enum_redaction import RedactionEnumREDACTION -from typing import Optional, Set -from typing_extensions import Self - -class V1DetokenizeRecordRequest(BaseModel): - """ - V1DetokenizeRecordRequest - """ # noqa: E501 - token: Optional[StrictStr] = Field(default=None, description="Token that identifies the record to detokenize.") - redaction: Optional[RedactionEnumREDACTION] = RedactionEnumREDACTION.DEFAULT - __properties: ClassVar[List[str]] = ["token", "redaction"] - - 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 V1DetokenizeRecordRequest 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 V1DetokenizeRecordRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "token": obj.get("token"), - "redaction": obj.get("redaction") if obj.get("redaction") is not None else RedactionEnumREDACTION.DEFAULT - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_detokenize_record_response.py b/skyflow/generated/rest/models/v1_detokenize_record_response.py deleted file mode 100644 index 2da5d15d..00000000 --- a/skyflow/generated/rest/models/v1_detokenize_record_response.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.detokenize_record_response_value_type import DetokenizeRecordResponseValueType -from typing import Optional, Set -from typing_extensions import Self - -class V1DetokenizeRecordResponse(BaseModel): - """ - V1DetokenizeRecordResponse - """ # noqa: E501 - token: Optional[StrictStr] = Field(default=None, description="Token of the record.") - value_type: Optional[DetokenizeRecordResponseValueType] = Field(default=DetokenizeRecordResponseValueType.NONE, alias="valueType") - value: Optional[StrictStr] = Field(default=None, description="Data corresponding to the token.") - error: Optional[StrictStr] = Field(default=None, description="Error if token isn't found.") - __properties: ClassVar[List[str]] = ["token", "valueType", "value", "error"] - - 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 V1DetokenizeRecordResponse 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 V1DetokenizeRecordResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "token": obj.get("token"), - "valueType": obj.get("valueType") if obj.get("valueType") is not None else DetokenizeRecordResponseValueType.NONE, - "value": obj.get("value"), - "error": obj.get("error") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_detokenize_response.py b/skyflow/generated/rest/models/v1_detokenize_response.py deleted file mode 100644 index 34554aa0..00000000 --- a/skyflow/generated/rest/models/v1_detokenize_response.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_detokenize_record_response import V1DetokenizeRecordResponse -from typing import Optional, Set -from typing_extensions import Self - -class V1DetokenizeResponse(BaseModel): - """ - V1DetokenizeResponse - """ # noqa: E501 - records: Optional[List[V1DetokenizeRecordResponse]] = Field(default=None, description="Records corresponding to the specified tokens.") - __properties: ClassVar[List[str]] = ["records"] - - 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 V1DetokenizeResponse 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 records (list) - _items = [] - if self.records: - for _item_records in self.records: - if _item_records: - _items.append(_item_records.to_dict()) - _dict['records'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1DetokenizeResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "records": [V1DetokenizeRecordResponse.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_field_records.py b/skyflow/generated/rest/models/v1_field_records.py deleted file mode 100644 index 913fd6d0..00000000 --- a/skyflow/generated/rest/models/v1_field_records.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1FieldRecords(BaseModel): - """ - Record values and tokens. - """ # noqa: E501 - fields: Optional[Dict[str, Any]] = Field(default=None, description="Fields and values for the record. For example, `{'field_1':'value_1', 'field_2':'value_2'}`.") - tokens: Optional[Dict[str, Any]] = Field(default=None, description="Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`.") - __properties: ClassVar[List[str]] = ["fields", "tokens"] - - 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 V1FieldRecords 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 V1FieldRecords from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "fields": obj.get("fields"), - "tokens": obj.get("tokens") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_file_av_scan_status.py b/skyflow/generated/rest/models/v1_file_av_scan_status.py deleted file mode 100644 index 91479e32..00000000 --- a/skyflow/generated/rest/models/v1_file_av_scan_status.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 V1FileAVScanStatus(str, Enum): - """ - Anti-virus scan status of the file. - """ - - """ - allowed enum values - """ - SCAN_NONE = 'SCAN_NONE' - SCAN_CLEAN = 'SCAN_CLEAN' - SCAN_INFECTED = 'SCAN_INFECTED' - SCAN_DELETED = 'SCAN_DELETED' - SCAN_ERROR = 'SCAN_ERROR' - SCAN_PENDING = 'SCAN_PENDING' - SCAN_UNSCANNABLE = 'SCAN_UNSCANNABLE' - SCAN_FILE_NOT_FOUND = 'SCAN_FILE_NOT_FOUND' - SCAN_INVALID = 'SCAN_INVALID' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of V1FileAVScanStatus from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/v1_get_auth_token_request.py b/skyflow/generated/rest/models/v1_get_auth_token_request.py deleted file mode 100644 index fd5b201f..00000000 --- a/skyflow/generated/rest/models/v1_get_auth_token_request.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Management API - - # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1GetAuthTokenRequest(BaseModel): - """ - V1GetAuthTokenRequest - """ # noqa: E501 - grant_type: StrictStr = Field(description="Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`.") - assertion: StrictStr = Field(description="User-signed JWT token that contains the following fields:
  • iss: Issuer of the JWT.
  • key: Unique identifier for the key.
  • aud: Recipient the JWT is intended for.
  • exp: Time the JWT expires.
  • sub: Subject of the JWT.
  • ctx: (Optional) Value for Context-aware authorization.
") - subject_token: Optional[StrictStr] = Field(default=None, description="Subject token.") - subject_token_type: Optional[StrictStr] = Field(default=None, description="Subject token type.") - requested_token_use: Optional[StrictStr] = Field(default=None, description="Token use type. Either `delegation` or `impersonation`.") - scope: Optional[StrictStr] = Field(default=None, description="Subset of available roles to associate with the requested token. Uses the format \"role:\\ role:\\\".") - __properties: ClassVar[List[str]] = ["grant_type", "assertion", "subject_token", "subject_token_type", "requested_token_use", "scope"] - - 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 V1GetAuthTokenRequest 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 V1GetAuthTokenRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "grant_type": obj.get("grant_type"), - "assertion": obj.get("assertion"), - "subject_token": obj.get("subject_token"), - "subject_token_type": obj.get("subject_token_type"), - "requested_token_use": obj.get("requested_token_use"), - "scope": obj.get("scope") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_get_auth_token_response.py b/skyflow/generated/rest/models/v1_get_auth_token_response.py deleted file mode 100644 index c3fccac2..00000000 --- a/skyflow/generated/rest/models/v1_get_auth_token_response.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Management API - - # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1GetAuthTokenResponse(BaseModel): - """ - V1GetAuthTokenResponse - """ # noqa: E501 - access_token: Optional[StrictStr] = Field(default=None, description="AccessToken.", alias="accessToken") - token_type: Optional[StrictStr] = Field(default=None, description="TokenType : Bearer.", alias="tokenType") - __properties: ClassVar[List[str]] = ["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 V1GetAuthTokenResponse 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 V1GetAuthTokenResponse 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"), - "tokenType": obj.get("tokenType") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_get_file_scan_status_response.py b/skyflow/generated/rest/models/v1_get_file_scan_status_response.py deleted file mode 100644 index 78d83d19..00000000 --- a/skyflow/generated/rest/models/v1_get_file_scan_status_response.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_file_av_scan_status import V1FileAVScanStatus -from typing import Optional, Set -from typing_extensions import Self - -class V1GetFileScanStatusResponse(BaseModel): - """ - V1GetFileScanStatusResponse - """ # noqa: E501 - av_scan_status: Optional[V1FileAVScanStatus] = V1FileAVScanStatus.SCAN_NONE - __properties: ClassVar[List[str]] = ["av_scan_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 V1GetFileScanStatusResponse 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 V1GetFileScanStatusResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "av_scan_status": obj.get("av_scan_status") if obj.get("av_scan_status") is not None else V1FileAVScanStatus.NONE - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_get_query_response.py b/skyflow/generated/rest/models/v1_get_query_response.py deleted file mode 100644 index 3f7dd870..00000000 --- a/skyflow/generated/rest/models/v1_get_query_response.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_field_records import V1FieldRecords -from typing import Optional, Set -from typing_extensions import Self - -class V1GetQueryResponse(BaseModel): - """ - V1GetQueryResponse - """ # noqa: E501 - records: Optional[List[V1FieldRecords]] = Field(default=None, description="Records returned by the query.") - __properties: ClassVar[List[str]] = ["records"] - - 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 V1GetQueryResponse 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 records (list) - _items = [] - if self.records: - for _item_records in self.records: - if _item_records: - _items.append(_item_records.to_dict()) - _dict['records'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1GetQueryResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "records": [V1FieldRecords.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_insert_record_response.py b/skyflow/generated/rest/models/v1_insert_record_response.py deleted file mode 100644 index 142f1304..00000000 --- a/skyflow/generated/rest/models/v1_insert_record_response.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_record_meta_properties import V1RecordMetaProperties -from typing import Optional, Set -from typing_extensions import Self - -class V1InsertRecordResponse(BaseModel): - """ - V1InsertRecordResponse - """ # noqa: E501 - records: Optional[List[V1RecordMetaProperties]] = Field(default=None, description="Identifiers for the inserted records.") - __properties: ClassVar[List[str]] = ["records"] - - 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 V1InsertRecordResponse 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 records (list) - _items = [] - if self.records: - for _item_records in self.records: - if _item_records: - _items.append(_item_records.to_dict()) - _dict['records'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1InsertRecordResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "records": [V1RecordMetaProperties.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_member_type.py b/skyflow/generated/rest/models/v1_member_type.py deleted file mode 100644 index 60009732..00000000 --- a/skyflow/generated/rest/models/v1_member_type.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 V1MemberType(str, Enum): - """ - Type of the member. - """ - - """ - allowed enum values - """ - NONE = 'NONE' - USER = 'USER' - SERVICE_ACCOUNT = 'SERVICE_ACCOUNT' - - @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of V1MemberType from a JSON string""" - return cls(json.loads(json_str)) - - diff --git a/skyflow/generated/rest/models/v1_record_meta_properties.py b/skyflow/generated/rest/models/v1_record_meta_properties.py deleted file mode 100644 index add596f2..00000000 --- a/skyflow/generated/rest/models/v1_record_meta_properties.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1RecordMetaProperties(BaseModel): - """ - V1RecordMetaProperties - """ # noqa: E501 - skyflow_id: Optional[StrictStr] = Field(default=None, description="ID of the inserted record.") - tokens: Optional[Dict[str, Any]] = Field(default=None, description="Tokens for the record.") - __properties: ClassVar[List[str]] = ["skyflow_id", "tokens"] - - 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 V1RecordMetaProperties 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 V1RecordMetaProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skyflow_id": obj.get("skyflow_id"), - "tokens": obj.get("tokens") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_tokenize_payload.py b/skyflow/generated/rest/models/v1_tokenize_payload.py deleted file mode 100644 index 8a275f2b..00000000 --- a/skyflow/generated/rest/models/v1_tokenize_payload.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_tokenize_record_request import V1TokenizeRecordRequest -from typing import Optional, Set -from typing_extensions import Self - -class V1TokenizePayload(BaseModel): - """ - V1TokenizePayload - """ # noqa: E501 - tokenization_parameters: Optional[List[V1TokenizeRecordRequest]] = Field(default=None, description="Tokenization details.", alias="tokenizationParameters") - __properties: ClassVar[List[str]] = ["tokenizationParameters"] - - 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 V1TokenizePayload 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 tokenization_parameters (list) - _items = [] - if self.tokenization_parameters: - for _item_tokenization_parameters in self.tokenization_parameters: - if _item_tokenization_parameters: - _items.append(_item_tokenization_parameters.to_dict()) - _dict['tokenizationParameters'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1TokenizePayload from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "tokenizationParameters": [V1TokenizeRecordRequest.from_dict(_item) for _item in obj["tokenizationParameters"]] if obj.get("tokenizationParameters") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_tokenize_record_request.py b/skyflow/generated/rest/models/v1_tokenize_record_request.py deleted file mode 100644 index e69e1e93..00000000 --- a/skyflow/generated/rest/models/v1_tokenize_record_request.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1TokenizeRecordRequest(BaseModel): - """ - V1TokenizeRecordRequest - """ # noqa: E501 - value: Optional[StrictStr] = Field(default=None, description="Existing value to return a token for.") - column_group: Optional[StrictStr] = Field(default=None, description="Name of the column group that the value belongs to.", alias="columnGroup") - __properties: ClassVar[List[str]] = ["value", "columnGroup"] - - 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 V1TokenizeRecordRequest 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 V1TokenizeRecordRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "value": obj.get("value"), - "columnGroup": obj.get("columnGroup") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_tokenize_record_response.py b/skyflow/generated/rest/models/v1_tokenize_record_response.py deleted file mode 100644 index 24ac8311..00000000 --- a/skyflow/generated/rest/models/v1_tokenize_record_response.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1TokenizeRecordResponse(BaseModel): - """ - V1TokenizeRecordResponse - """ # noqa: E501 - token: Optional[StrictStr] = Field(default=None, description="Token corresponding to a value.") - __properties: ClassVar[List[str]] = ["token"] - - 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 V1TokenizeRecordResponse 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 V1TokenizeRecordResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "token": obj.get("token") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_tokenize_response.py b/skyflow/generated/rest/models/v1_tokenize_response.py deleted file mode 100644 index 4847bae5..00000000 --- a/skyflow/generated/rest/models/v1_tokenize_response.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_tokenize_record_response import V1TokenizeRecordResponse -from typing import Optional, Set -from typing_extensions import Self - -class V1TokenizeResponse(BaseModel): - """ - V1TokenizeResponse - """ # noqa: E501 - records: Optional[List[V1TokenizeRecordResponse]] = Field(default=None, description="Tokens corresponding to the specified values.") - __properties: ClassVar[List[str]] = ["records"] - - 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 V1TokenizeResponse 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 records (list) - _items = [] - if self.records: - for _item_records in self.records: - if _item_records: - _items.append(_item_records.to_dict()) - _dict['records'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1TokenizeResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "records": [V1TokenizeRecordResponse.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_update_record_response.py b/skyflow/generated/rest/models/v1_update_record_response.py deleted file mode 100644 index 0d66a403..00000000 --- a/skyflow/generated/rest/models/v1_update_record_response.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1UpdateRecordResponse(BaseModel): - """ - V1UpdateRecordResponse - """ # noqa: E501 - skyflow_id: Optional[StrictStr] = Field(default=None, description="ID of the updated record.") - tokens: Optional[Dict[str, Any]] = Field(default=None, description="Tokens for the record.") - __properties: ClassVar[List[str]] = ["skyflow_id", "tokens"] - - 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 V1UpdateRecordResponse 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 V1UpdateRecordResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skyflow_id": obj.get("skyflow_id"), - "tokens": obj.get("tokens") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_vault_field_mapping.py b/skyflow/generated/rest/models/v1_vault_field_mapping.py deleted file mode 100644 index b00c92e5..00000000 --- a/skyflow/generated/rest/models/v1_vault_field_mapping.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from typing import Optional, Set -from typing_extensions import Self - -class V1VaultFieldMapping(BaseModel): - """ - Mapping of the fields in the vault to the fields to use for the lookup. - """ # noqa: E501 - card_number: Optional[StrictStr] = Field(default=None, description="Name of the column that stores the card number.") - card_last_four_digits: Optional[StrictStr] = Field(default=None, description="Name of the column that stores the card number suffix.") - card_expiry: Optional[StrictStr] = Field(default=None, description="Name of the column that stores the expiry date.") - __properties: ClassVar[List[str]] = ["card_number", "card_last_four_digits", "card_expiry"] - - 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 V1VaultFieldMapping 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 V1VaultFieldMapping from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "card_number": obj.get("card_number"), - "card_last_four_digits": obj.get("card_last_four_digits"), - "card_expiry": obj.get("card_expiry") - }) - return _obj - - diff --git a/skyflow/generated/rest/models/v1_vault_schema_config.py b/skyflow/generated/rest/models/v1_vault_schema_config.py deleted file mode 100644 index e57e21ff..00000000 --- a/skyflow/generated/rest/models/v1_vault_schema_config.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
  • Production: https://*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from skyflow.generated.rest.models.v1_vault_field_mapping import V1VaultFieldMapping -from typing import Optional, Set -from typing_extensions import Self - -class V1VaultSchemaConfig(BaseModel): - """ - Details of the vault that stores additional card details. - """ # noqa: E501 - id: Optional[StrictStr] = Field(default=None, description="ID of the vault that stores card details.") - table_name: Optional[StrictStr] = Field(default=None, description="Name of the table that stores card details.") - mapping: Optional[V1VaultFieldMapping] = None - __properties: ClassVar[List[str]] = ["id", "table_name", "mapping"] - - 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 V1VaultSchemaConfig 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 mapping - if self.mapping: - _dict['mapping'] = self.mapping.to_dict() - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of V1VaultSchemaConfig 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"), - "table_name": obj.get("table_name"), - "mapping": V1VaultFieldMapping.from_dict(obj["mapping"]) if obj.get("mapping") is not None else None - }) - return _obj - - diff --git a/skyflow/generated/rest/query/__init__.py b/skyflow/generated/rest/query/__init__.py new file mode 100644 index 00000000..f3ea2659 --- /dev/null +++ b/skyflow/generated/rest/query/__init__.py @@ -0,0 +1,2 @@ +# This file was auto-generated by Fern from our API Definition. + diff --git a/skyflow/generated/rest/query/client.py b/skyflow/generated/rest/query/client.py new file mode 100644 index 00000000..cf3ca319 --- /dev/null +++ b/skyflow/generated/rest/query/client.py @@ -0,0 +1,181 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from ..types.v_1_get_query_response import V1GetQueryResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..errors.not_found_error import NotFoundError +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class QueryClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def query_service_execute_query( + self, + vault_id: str, + *, + query: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1GetQueryResponse: + """ + Returns records for a valid SQL query. This endpoint
  • Can return redacted record values.
  • Supports only the SELECT command.
  • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
  • Can't modify the vault or perform transactions.
  • Can't return tokens.
  • Can't return file download or render URLs.
  • Doesn't support the WHERE keyword with columns using transient tokenization.
  • Doesn't support `?` conditional for columns with column-level encryption disabled.
    • + + Parameters + ---------- + vault_id : str + ID of the vault. + + query : typing.Optional[str] + The SQL query to execute.

      Supported commands:
      • SELECT
      Supported operators:
      • >
      • <
      • =
      • AND
      • OR
      • NOT
      • LIKE
      • ILIKE
      • NULL
      • NOT NULL
      Supported keywords:
      • FROM
      • JOIN
      • INNER JOIN
      • LEFT OUTER JOIN
      • LEFT JOIN
      • RIGHT OUTER JOIN
      • RIGHT JOIN
      • FULL OUTER JOIN
      • FULL JOIN
      • OFFSET
      • LIMIT
      • WHERE
      Supported functions:
      • AVG()
      • SUM()
      • COUNT()
      • MIN()
      • MAX()
      • REDACTION()
      + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1GetQueryResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.query.query_service_execute_query( + vault_id="vaultID", + query='select * from opportunities where id="01010000ade21cded569d43944544ec6"', + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/query", + method="POST", + json={ + "query": query, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1GetQueryResponse, + parse_obj_as( + type_=V1GetQueryResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + +class AsyncQueryClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def query_service_execute_query( + self, + vault_id: str, + *, + query: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1GetQueryResponse: + """ + Returns records for a valid SQL query. This endpoint
      • Can return redacted record values.
      • Supports only the SELECT command.
      • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
      • Can't modify the vault or perform transactions.
      • Can't return tokens.
      • Can't return file download or render URLs.
      • Doesn't support the WHERE keyword with columns using transient tokenization.
      • Doesn't support `?` conditional for columns with column-level encryption disabled.
        • + + Parameters + ---------- + vault_id : str + ID of the vault. + + query : typing.Optional[str] + The SQL query to execute.

          Supported commands:
          • SELECT
          Supported operators:
          • >
          • <
          • =
          • AND
          • OR
          • NOT
          • LIKE
          • ILIKE
          • NULL
          • NOT NULL
          Supported keywords:
          • FROM
          • JOIN
          • INNER JOIN
          • LEFT OUTER JOIN
          • LEFT JOIN
          • RIGHT OUTER JOIN
          • RIGHT JOIN
          • FULL OUTER JOIN
          • FULL JOIN
          • OFFSET
          • LIMIT
          • WHERE
          Supported functions:
          • AVG()
          • SUM()
          • COUNT()
          • MIN()
          • MAX()
          • REDACTION()
          + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1GetQueryResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.query.query_service_execute_query( + vault_id="vaultID", + query='select * from opportunities where id="01010000ade21cded569d43944544ec6"', + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/query", + method="POST", + json={ + "query": query, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1GetQueryResponse, + parse_obj_as( + type_=V1GetQueryResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/records/__init__.py b/skyflow/generated/rest/records/__init__.py new file mode 100644 index 00000000..b144d479 --- /dev/null +++ b/skyflow/generated/rest/records/__init__.py @@ -0,0 +1,13 @@ +# This file was auto-generated by Fern from our API Definition. + +from .types import ( + RecordServiceBulkGetRecordRequestOrderBy, + RecordServiceBulkGetRecordRequestRedaction, + RecordServiceGetRecordRequestRedaction, +) + +__all__ = [ + "RecordServiceBulkGetRecordRequestOrderBy", + "RecordServiceBulkGetRecordRequestRedaction", + "RecordServiceGetRecordRequestRedaction", +] diff --git a/skyflow/generated/rest/records/client.py b/skyflow/generated/rest/records/client.py new file mode 100644 index 00000000..d73e0da0 --- /dev/null +++ b/skyflow/generated/rest/records/client.py @@ -0,0 +1,1978 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from ..core.client_wrapper import SyncClientWrapper +from ..types.v_1_batch_record import V1BatchRecord +from ..types.v_1_byot import V1Byot +from ..core.request_options import RequestOptions +from ..types.v_1_batch_operation_response import V1BatchOperationResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.serialization import convert_and_respect_annotation_metadata +from ..core.pydantic_utilities import parse_obj_as +from ..errors.not_found_error import NotFoundError +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from .types.record_service_bulk_get_record_request_redaction import RecordServiceBulkGetRecordRequestRedaction +from .types.record_service_bulk_get_record_request_order_by import RecordServiceBulkGetRecordRequestOrderBy +from ..types.v_1_bulk_get_record_response import V1BulkGetRecordResponse +from ..types.v_1_field_records import V1FieldRecords +from ..types.v_1_insert_record_response import V1InsertRecordResponse +from ..types.v_1_bulk_delete_record_response import V1BulkDeleteRecordResponse +from .types.record_service_get_record_request_redaction import RecordServiceGetRecordRequestRedaction +from ..types.v_1_update_record_response import V1UpdateRecordResponse +from ..types.v_1_delete_record_response import V1DeleteRecordResponse +from .. import core +from ..types.v_1_delete_file_response import V1DeleteFileResponse +from ..types.v_1_get_file_scan_status_response import V1GetFileScanStatusResponse +from ..core.client_wrapper import AsyncClientWrapper + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RecordsClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def record_service_batch_operation( + self, + vault_id: str, + *, + records: typing.Optional[typing.Sequence[V1BatchRecord]] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BatchOperationResponse: + """ + Performs multiple record operations in a single transaction. + + Parameters + ---------- + vault_id : str + ID of the vault. + + records : typing.Optional[typing.Sequence[V1BatchRecord]] + Record operations to perform. + + continue_on_error : typing.Optional[bool] + Continue performing operations on partial errors. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BatchOperationResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow, V1BatchRecord + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.record_service_batch_operation( + vault_id="vaultID", + records=[ + V1BatchRecord( + fields={ + "drivers_license_number": "89867453", + "name": "Connor", + "phone_number": "8794523160", + "ssn": "143-89-2306", + }, + table_name="persons", + method="POST", + batch_id="persons-12345", + redaction="PLAIN_TEXT", + tokenization=False, + download_url=False, + upsert="drivers_license_number", + ), + V1BatchRecord( + table_name="persons", + method="GET", + batch_id="persons-12345", + redaction="PLAIN_TEXT", + tokenization=False, + id="f1dbc55c-7c9b-495d-9a36-72bb2b619202", + download_url=True, + ), + ], + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write" + ), + "continueOnError": continue_on_error, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BatchOperationResponse, + parse_obj_as( + type_=V1BatchOperationResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def record_service_bulk_get_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + redaction: typing.Optional[RecordServiceBulkGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + offset: typing.Optional[str] = None, + limit: typing.Optional[str] = None, + download_url: typing.Optional[bool] = None, + column_name: typing.Optional[str] = None, + column_values: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + order_by: typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BulkGetRecordResponse: + """ + Gets the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table that contains the records. + + skyflow_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]] + `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

          If not specified, returns the first 25 records in the table. + + redaction : typing.Optional[RecordServiceBulkGetRecordRequestRedaction] + Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + offset : typing.Optional[str] + Record position at which to start receiving data. + + limit : typing.Optional[str] + Number of record to return. Maximum 25. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + column_name : typing.Optional[str] + Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + column_values : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

          `column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + order_by : typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] + Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BulkGetRecordResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.record_service_bulk_get_record( + vault_id="vaultID", + object_name="objectName", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="GET", + params={ + "skyflow_ids": skyflow_ids, + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "offset": offset, + "limit": limit, + "downloadURL": download_url, + "column_name": column_name, + "column_values": column_values, + "order_by": order_by, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BulkGetRecordResponse, + parse_obj_as( + type_=V1BulkGetRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def record_service_insert_record( + self, + vault_id: str, + object_name: str, + *, + records: typing.Optional[typing.Sequence[V1FieldRecords]] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + upsert: typing.Optional[str] = OMIT, + homogeneous: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1InsertRecordResponse: + """ + Inserts a record in the specified table.

          The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.

          Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + records : typing.Optional[typing.Sequence[V1FieldRecords]] + Record values and tokens. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + upsert : typing.Optional[str] + Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.

          When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. + + homogeneous : typing.Optional[bool] + If `true`, this operation mandates that all the records have the same fields. This parameter does not work with upsert. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1InsertRecordResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow, V1FieldRecords + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.record_service_insert_record( + vault_id="vaultID", + object_name="objectName", + records=[ + V1FieldRecords( + fields={ + "drivers_license_number": "13456789", + "name": "John", + "phone_number": "1236784563", + "ssn": "123-45-6789", + }, + ), + V1FieldRecords( + fields={ + "drivers_license_number": "98765432", + "name": "James", + "phone_number": "9876543215", + "ssn": "345-45-9876", + }, + ), + ], + tokenization=True, + upsert="drivers_license_number", + homogeneous=False, + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1FieldRecords], direction="write" + ), + "tokenization": tokenization, + "upsert": upsert, + "homogeneous": homogeneous, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1InsertRecordResponse, + parse_obj_as( + type_=V1InsertRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def record_service_bulk_delete_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Sequence[str]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BulkDeleteRecordResponse: + """ + Deletes the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + skyflow_ids : typing.Optional[typing.Sequence[str]] + `skyflow_id` values of the records to delete. If `*` is specified, this operation deletes all records in the table. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BulkDeleteRecordResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.record_service_bulk_delete_record( + vault_id="vaultID", + object_name="objectName", + skyflow_ids=[ + "51782ea4-91a5-4430-a06d-f4b76efd3d2f", + "110ce08f-6059-4874-b1ae-7c6651d286ff", + ], + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="DELETE", + json={ + "skyflow_ids": skyflow_ids, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BulkDeleteRecordResponse, + parse_obj_as( + type_=V1BulkDeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def record_service_get_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + redaction: typing.Optional[RecordServiceGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + download_url: typing.Optional[bool] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1FieldRecords: + """ + Returns the specified record from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + redaction : typing.Optional[RecordServiceGetRecordRequestRedaction] + Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1FieldRecords + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.record_service_get_record( + vault_id="vaultID", + object_name="objectName", + id="ID", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="GET", + params={ + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "downloadURL": download_url, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1FieldRecords, + parse_obj_as( + type_=V1FieldRecords, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def record_service_update_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + record: typing.Optional[V1FieldRecords] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1UpdateRecordResponse: + """ + Updates the specified record in a table.

          When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

          The time-to-live (TTL) for a transient field resets when the field value is updated. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + record : typing.Optional[V1FieldRecords] + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1UpdateRecordResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow, V1FieldRecords + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.record_service_update_record( + vault_id="vaultID", + object_name="objectName", + id="ID", + record=V1FieldRecords( + fields={ + "drivers_license_number": "89867453", + "name": "Steve Smith", + "phone_number": "8794523160", + "ssn": "143-89-2306", + }, + ), + tokenization=True, + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="PUT", + json={ + "record": convert_and_respect_annotation_metadata( + object_=record, annotation=V1FieldRecords, direction="write" + ), + "tokenization": tokenization, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def record_service_delete_record( + self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> V1DeleteRecordResponse: + """ + Deletes the specified record from a table.

          Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record to delete. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1DeleteRecordResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.record_service_delete_record( + vault_id="vaultID", + object_name="objectName", + id="ID", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1DeleteRecordResponse, + parse_obj_as( + type_=V1DeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def file_service_upload_file( + self, + vault_id: str, + object_name: str, + id: str, + *, + file_column_name: typing.Optional[core.File] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1UpdateRecordResponse: + """ + Uploads a file to the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + file_column_name : typing.Optional[core.File] + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1UpdateRecordResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.file_service_upload_file( + vault_id="vaultID", + object_name="objectName", + id="ID", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}/files", + method="POST", + data={}, + files={ + "fileColumnName": file_column_name, + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def file_service_delete_file( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1DeleteFileResponse: + """ + Deletes a file from the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1DeleteFileResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.file_service_delete_file( + vault_id="vaultID", + table_name="tableName", + id="ID", + column_name="columnName", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1DeleteFileResponse, + parse_obj_as( + type_=V1DeleteFileResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def file_service_get_file_scan_status( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1GetFileScanStatusResponse: + """ + Returns the anti-virus scan status of a file. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1GetFileScanStatusResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.records.file_service_get_file_scan_status( + vault_id="vaultID", + table_name="tableName", + id="ID", + column_name="columnName", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}/scan-status", + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1GetFileScanStatusResponse, + parse_obj_as( + type_=V1GetFileScanStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + +class AsyncRecordsClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def record_service_batch_operation( + self, + vault_id: str, + *, + records: typing.Optional[typing.Sequence[V1BatchRecord]] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BatchOperationResponse: + """ + Performs multiple record operations in a single transaction. + + Parameters + ---------- + vault_id : str + ID of the vault. + + records : typing.Optional[typing.Sequence[V1BatchRecord]] + Record operations to perform. + + continue_on_error : typing.Optional[bool] + Continue performing operations on partial errors. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BatchOperationResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow, V1BatchRecord + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.record_service_batch_operation( + vault_id="vaultID", + records=[ + V1BatchRecord( + fields={ + "drivers_license_number": "89867453", + "name": "Connor", + "phone_number": "8794523160", + "ssn": "143-89-2306", + }, + table_name="persons", + method="POST", + batch_id="persons-12345", + redaction="PLAIN_TEXT", + tokenization=False, + download_url=False, + upsert="drivers_license_number", + ), + V1BatchRecord( + table_name="persons", + method="GET", + batch_id="persons-12345", + redaction="PLAIN_TEXT", + tokenization=False, + id="f1dbc55c-7c9b-495d-9a36-72bb2b619202", + download_url=True, + ), + ], + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write" + ), + "continueOnError": continue_on_error, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BatchOperationResponse, + parse_obj_as( + type_=V1BatchOperationResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def record_service_bulk_get_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + redaction: typing.Optional[RecordServiceBulkGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + offset: typing.Optional[str] = None, + limit: typing.Optional[str] = None, + download_url: typing.Optional[bool] = None, + column_name: typing.Optional[str] = None, + column_values: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + order_by: typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BulkGetRecordResponse: + """ + Gets the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table that contains the records. + + skyflow_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]] + `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

          If not specified, returns the first 25 records in the table. + + redaction : typing.Optional[RecordServiceBulkGetRecordRequestRedaction] + Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + offset : typing.Optional[str] + Record position at which to start receiving data. + + limit : typing.Optional[str] + Number of record to return. Maximum 25. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + column_name : typing.Optional[str] + Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + column_values : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

          `column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + order_by : typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] + Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BulkGetRecordResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.record_service_bulk_get_record( + vault_id="vaultID", + object_name="objectName", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="GET", + params={ + "skyflow_ids": skyflow_ids, + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "offset": offset, + "limit": limit, + "downloadURL": download_url, + "column_name": column_name, + "column_values": column_values, + "order_by": order_by, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BulkGetRecordResponse, + parse_obj_as( + type_=V1BulkGetRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def record_service_insert_record( + self, + vault_id: str, + object_name: str, + *, + records: typing.Optional[typing.Sequence[V1FieldRecords]] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + upsert: typing.Optional[str] = OMIT, + homogeneous: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1InsertRecordResponse: + """ + Inserts a record in the specified table.

          The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.

          Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + records : typing.Optional[typing.Sequence[V1FieldRecords]] + Record values and tokens. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + upsert : typing.Optional[str] + Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.

          When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. + + homogeneous : typing.Optional[bool] + If `true`, this operation mandates that all the records have the same fields. This parameter does not work with upsert. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1InsertRecordResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow, V1FieldRecords + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.record_service_insert_record( + vault_id="vaultID", + object_name="objectName", + records=[ + V1FieldRecords( + fields={ + "drivers_license_number": "13456789", + "name": "John", + "phone_number": "1236784563", + "ssn": "123-45-6789", + }, + ), + V1FieldRecords( + fields={ + "drivers_license_number": "98765432", + "name": "James", + "phone_number": "9876543215", + "ssn": "345-45-9876", + }, + ), + ], + tokenization=True, + upsert="drivers_license_number", + homogeneous=False, + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1FieldRecords], direction="write" + ), + "tokenization": tokenization, + "upsert": upsert, + "homogeneous": homogeneous, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1InsertRecordResponse, + parse_obj_as( + type_=V1InsertRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def record_service_bulk_delete_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Sequence[str]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1BulkDeleteRecordResponse: + """ + Deletes the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + skyflow_ids : typing.Optional[typing.Sequence[str]] + `skyflow_id` values of the records to delete. If `*` is specified, this operation deletes all records in the table. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1BulkDeleteRecordResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.record_service_bulk_delete_record( + vault_id="vaultID", + object_name="objectName", + skyflow_ids=[ + "51782ea4-91a5-4430-a06d-f4b76efd3d2f", + "110ce08f-6059-4874-b1ae-7c6651d286ff", + ], + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="DELETE", + json={ + "skyflow_ids": skyflow_ids, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1BulkDeleteRecordResponse, + parse_obj_as( + type_=V1BulkDeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def record_service_get_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + redaction: typing.Optional[RecordServiceGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + download_url: typing.Optional[bool] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1FieldRecords: + """ + Returns the specified record from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + redaction : typing.Optional[RecordServiceGetRecordRequestRedaction] + Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1FieldRecords + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.record_service_get_record( + vault_id="vaultID", + object_name="objectName", + id="ID", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="GET", + params={ + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "downloadURL": download_url, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1FieldRecords, + parse_obj_as( + type_=V1FieldRecords, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def record_service_update_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + record: typing.Optional[V1FieldRecords] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1UpdateRecordResponse: + """ + Updates the specified record in a table.

          When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

          The time-to-live (TTL) for a transient field resets when the field value is updated. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + record : typing.Optional[V1FieldRecords] + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1UpdateRecordResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow, V1FieldRecords + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.record_service_update_record( + vault_id="vaultID", + object_name="objectName", + id="ID", + record=V1FieldRecords( + fields={ + "drivers_license_number": "89867453", + "name": "Steve Smith", + "phone_number": "8794523160", + "ssn": "143-89-2306", + }, + ), + tokenization=True, + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="PUT", + json={ + "record": convert_and_respect_annotation_metadata( + object_=record, annotation=V1FieldRecords, direction="write" + ), + "tokenization": tokenization, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def record_service_delete_record( + self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> V1DeleteRecordResponse: + """ + Deletes the specified record from a table.

          Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record to delete. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1DeleteRecordResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.record_service_delete_record( + vault_id="vaultID", + object_name="objectName", + id="ID", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1DeleteRecordResponse, + parse_obj_as( + type_=V1DeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def file_service_upload_file( + self, + vault_id: str, + object_name: str, + id: str, + *, + file_column_name: typing.Optional[core.File] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1UpdateRecordResponse: + """ + Uploads a file to the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + file_column_name : typing.Optional[core.File] + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1UpdateRecordResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.file_service_upload_file( + vault_id="vaultID", + object_name="objectName", + id="ID", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}/files", + method="POST", + data={}, + files={ + "fileColumnName": file_column_name, + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def file_service_delete_file( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1DeleteFileResponse: + """ + Deletes a file from the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1DeleteFileResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.file_service_delete_file( + vault_id="vaultID", + table_name="tableName", + id="ID", + column_name="columnName", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1DeleteFileResponse, + parse_obj_as( + type_=V1DeleteFileResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def file_service_get_file_scan_status( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1GetFileScanStatusResponse: + """ + Returns the anti-virus scan status of a file. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1GetFileScanStatusResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.records.file_service_get_file_scan_status( + vault_id="vaultID", + table_name="tableName", + id="ID", + column_name="columnName", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}/scan-status", + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1GetFileScanStatusResponse, + parse_obj_as( + type_=V1GetFileScanStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/records/types/__init__.py b/skyflow/generated/rest/records/types/__init__.py new file mode 100644 index 00000000..9e9ce24e --- /dev/null +++ b/skyflow/generated/rest/records/types/__init__.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +from .record_service_bulk_get_record_request_order_by import RecordServiceBulkGetRecordRequestOrderBy +from .record_service_bulk_get_record_request_redaction import RecordServiceBulkGetRecordRequestRedaction +from .record_service_get_record_request_redaction import RecordServiceGetRecordRequestRedaction + +__all__ = [ + "RecordServiceBulkGetRecordRequestOrderBy", + "RecordServiceBulkGetRecordRequestRedaction", + "RecordServiceGetRecordRequestRedaction", +] diff --git a/skyflow/generated/rest/records/types/record_service_bulk_get_record_request_order_by.py b/skyflow/generated/rest/records/types/record_service_bulk_get_record_request_order_by.py new file mode 100644 index 00000000..41f10c0b --- /dev/null +++ b/skyflow/generated/rest/records/types/record_service_bulk_get_record_request_order_by.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +RecordServiceBulkGetRecordRequestOrderBy = typing.Union[typing.Literal["ASCENDING", "DESCENDING", "NONE"], typing.Any] diff --git a/skyflow/generated/rest/records/types/record_service_bulk_get_record_request_redaction.py b/skyflow/generated/rest/records/types/record_service_bulk_get_record_request_redaction.py new file mode 100644 index 00000000..69bf6788 --- /dev/null +++ b/skyflow/generated/rest/records/types/record_service_bulk_get_record_request_redaction.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +RecordServiceBulkGetRecordRequestRedaction = typing.Union[ + typing.Literal["DEFAULT", "REDACTED", "MASKED", "PLAIN_TEXT"], typing.Any +] diff --git a/skyflow/generated/rest/records/types/record_service_get_record_request_redaction.py b/skyflow/generated/rest/records/types/record_service_get_record_request_redaction.py new file mode 100644 index 00000000..d7de8c1a --- /dev/null +++ b/skyflow/generated/rest/records/types/record_service_get_record_request_redaction.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +RecordServiceGetRecordRequestRedaction = typing.Union[ + typing.Literal["DEFAULT", "REDACTED", "MASKED", "PLAIN_TEXT"], typing.Any +] diff --git a/skyflow/generated/rest/rest.py b/skyflow/generated/rest/rest.py deleted file mode 100644 index 1aaefdb3..00000000 --- a/skyflow/generated/rest/rest.py +++ /dev/null @@ -1,258 +0,0 @@ -# coding: utf-8 - -""" - Skyflow Data API - - # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
          • Sandbox: https://*identifier*.vault.skyflowapis-preview.com
          • Production: https://*identifier*.vault.skyflowapis.com
          When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- - The version of the OpenAPI document: v1 - Contact: support@skyflow.com - 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 skyflow.generated.rest.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'] == 'text/plain' 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/skyflow/generated/rest/tokens/__init__.py b/skyflow/generated/rest/tokens/__init__.py new file mode 100644 index 00000000..f3ea2659 --- /dev/null +++ b/skyflow/generated/rest/tokens/__init__.py @@ -0,0 +1,2 @@ +# This file was auto-generated by Fern from our API Definition. + diff --git a/skyflow/generated/rest/tokens/client.py b/skyflow/generated/rest/tokens/client.py new file mode 100644 index 00000000..641050fe --- /dev/null +++ b/skyflow/generated/rest/tokens/client.py @@ -0,0 +1,395 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from ..core.client_wrapper import SyncClientWrapper +from ..types.v_1_detokenize_record_request import V1DetokenizeRecordRequest +from ..core.request_options import RequestOptions +from ..types.v_1_detokenize_response import V1DetokenizeResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.serialization import convert_and_respect_annotation_metadata +from ..core.pydantic_utilities import parse_obj_as +from ..errors.not_found_error import NotFoundError +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..types.v_1_tokenize_record_request import V1TokenizeRecordRequest +from ..types.v_1_tokenize_response import V1TokenizeResponse +from ..core.client_wrapper import AsyncClientWrapper + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class TokensClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def record_service_detokenize( + self, + vault_id: str, + *, + detokenization_parameters: typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] = OMIT, + download_url: typing.Optional[bool] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1DetokenizeResponse: + """ + Returns records that correspond to the specified tokens. + + Parameters + ---------- + vault_id : str + ID of the vault. + + detokenization_parameters : typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] + Detokenization details. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + continue_on_error : typing.Optional[bool] + If `true`, the detokenization request continues even if an error occurs. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1DetokenizeResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow, V1DetokenizeRecordRequest + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.tokens.record_service_detokenize( + vault_id="vaultID", + detokenization_parameters=[ + V1DetokenizeRecordRequest( + token="afbd1074-51c1-4a16-9eee-e2c0ecb52125", + redaction="PLAIN_TEXT", + ), + V1DetokenizeRecordRequest( + token="05383487-fcae-42e5-a48e-5bd62a51af12", + redaction="DEFAULT", + ), + ], + download_url=False, + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/detokenize", + method="POST", + json={ + "detokenizationParameters": convert_and_respect_annotation_metadata( + object_=detokenization_parameters, + annotation=typing.Sequence[V1DetokenizeRecordRequest], + direction="write", + ), + "downloadURL": download_url, + "continueOnError": continue_on_error, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1DetokenizeResponse, + parse_obj_as( + type_=V1DetokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + def record_service_tokenize( + self, + vault_id: str, + *, + tokenization_parameters: typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1TokenizeResponse: + """ + Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.

Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see Insert Record and the tokenization parameter. + + Parameters + ---------- + vault_id : str + ID of the vault. + + tokenization_parameters : typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] + Tokenization details. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1TokenizeResponse + A successful response. + + Examples + -------- + from skyflow import Skyflow + + client = Skyflow( + token="YOUR_TOKEN", + ) + client.tokens.record_service_tokenize( + vault_id="vaultID", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/tokenize", + method="POST", + json={ + "tokenizationParameters": convert_and_respect_annotation_metadata( + object_=tokenization_parameters, + annotation=typing.Sequence[V1TokenizeRecordRequest], + direction="write", + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1TokenizeResponse, + parse_obj_as( + type_=V1TokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + +class AsyncTokensClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def record_service_detokenize( + self, + vault_id: str, + *, + detokenization_parameters: typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] = OMIT, + download_url: typing.Optional[bool] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1DetokenizeResponse: + """ + Returns records that correspond to the specified tokens. + + Parameters + ---------- + vault_id : str + ID of the vault. + + detokenization_parameters : typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] + Detokenization details. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + continue_on_error : typing.Optional[bool] + If `true`, the detokenization request continues even if an error occurs. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1DetokenizeResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow, V1DetokenizeRecordRequest + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.tokens.record_service_detokenize( + vault_id="vaultID", + detokenization_parameters=[ + V1DetokenizeRecordRequest( + token="afbd1074-51c1-4a16-9eee-e2c0ecb52125", + redaction="PLAIN_TEXT", + ), + V1DetokenizeRecordRequest( + token="05383487-fcae-42e5-a48e-5bd62a51af12", + redaction="DEFAULT", + ), + ], + download_url=False, + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/detokenize", + method="POST", + json={ + "detokenizationParameters": convert_and_respect_annotation_metadata( + object_=detokenization_parameters, + annotation=typing.Sequence[V1DetokenizeRecordRequest], + direction="write", + ), + "downloadURL": download_url, + "continueOnError": continue_on_error, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1DetokenizeResponse, + parse_obj_as( + type_=V1DetokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) + + async def record_service_tokenize( + self, + vault_id: str, + *, + tokenization_parameters: typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> V1TokenizeResponse: + """ + Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.

Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see Insert Record and the tokenization parameter. + + Parameters + ---------- + vault_id : str + ID of the vault. + + tokenization_parameters : typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] + Tokenization details. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + V1TokenizeResponse + A successful response. + + Examples + -------- + import asyncio + + from skyflow import AsyncSkyflow + + client = AsyncSkyflow( + token="YOUR_TOKEN", + ) + + + async def main() -> None: + await client.tokens.record_service_tokenize( + vault_id="vaultID", + ) + + + asyncio.run(main()) + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/tokenize", + method="POST", + json={ + "tokenizationParameters": convert_and_respect_annotation_metadata( + object_=tokenization_parameters, + annotation=typing.Sequence[V1TokenizeRecordRequest], + direction="write", + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + return typing.cast( + V1TokenizeResponse, + parse_obj_as( + type_=V1TokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, body=_response.text) + raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/types/__init__.py b/skyflow/generated/rest/types/__init__.py new file mode 100644 index 00000000..d2112008 --- /dev/null +++ b/skyflow/generated/rest/types/__init__.py @@ -0,0 +1,91 @@ +# This file was auto-generated by Fern from our API Definition. + +from .audit_event_audit_resource_type import AuditEventAuditResourceType +from .audit_event_context import AuditEventContext +from .audit_event_data import AuditEventData +from .audit_event_http_info import AuditEventHttpInfo +from .batch_record_method import BatchRecordMethod +from .context_access_type import ContextAccessType +from .context_auth_mode import ContextAuthMode +from .detokenize_record_response_value_type import DetokenizeRecordResponseValueType +from .googlerpc_status import GooglerpcStatus +from .protobuf_any import ProtobufAny +from .redaction_enum_redaction import RedactionEnumRedaction +from .request_action_type import RequestActionType +from .v_1_audit_after_options import V1AuditAfterOptions +from .v_1_audit_event_response import V1AuditEventResponse +from .v_1_audit_response import V1AuditResponse +from .v_1_audit_response_event import V1AuditResponseEvent +from .v_1_audit_response_event_request import V1AuditResponseEventRequest +from .v_1_batch_operation_response import V1BatchOperationResponse +from .v_1_batch_record import V1BatchRecord +from .v_1_bin_list_response import V1BinListResponse +from .v_1_bulk_delete_record_response import V1BulkDeleteRecordResponse +from .v_1_bulk_get_record_response import V1BulkGetRecordResponse +from .v_1_byot import V1Byot +from .v_1_card import V1Card +from .v_1_delete_file_response import V1DeleteFileResponse +from .v_1_delete_record_response import V1DeleteRecordResponse +from .v_1_detokenize_record_request import V1DetokenizeRecordRequest +from .v_1_detokenize_record_response import V1DetokenizeRecordResponse +from .v_1_detokenize_response import V1DetokenizeResponse +from .v_1_field_records import V1FieldRecords +from .v_1_file_av_scan_status import V1FileAvScanStatus +from .v_1_get_auth_token_response import V1GetAuthTokenResponse +from .v_1_get_file_scan_status_response import V1GetFileScanStatusResponse +from .v_1_get_query_response import V1GetQueryResponse +from .v_1_insert_record_response import V1InsertRecordResponse +from .v_1_member_type import V1MemberType +from .v_1_record_meta_properties import V1RecordMetaProperties +from .v_1_tokenize_record_request import V1TokenizeRecordRequest +from .v_1_tokenize_record_response import V1TokenizeRecordResponse +from .v_1_tokenize_response import V1TokenizeResponse +from .v_1_update_record_response import V1UpdateRecordResponse +from .v_1_vault_field_mapping import V1VaultFieldMapping +from .v_1_vault_schema_config import V1VaultSchemaConfig + +__all__ = [ + "AuditEventAuditResourceType", + "AuditEventContext", + "AuditEventData", + "AuditEventHttpInfo", + "BatchRecordMethod", + "ContextAccessType", + "ContextAuthMode", + "DetokenizeRecordResponseValueType", + "GooglerpcStatus", + "ProtobufAny", + "RedactionEnumRedaction", + "RequestActionType", + "V1AuditAfterOptions", + "V1AuditEventResponse", + "V1AuditResponse", + "V1AuditResponseEvent", + "V1AuditResponseEventRequest", + "V1BatchOperationResponse", + "V1BatchRecord", + "V1BinListResponse", + "V1BulkDeleteRecordResponse", + "V1BulkGetRecordResponse", + "V1Byot", + "V1Card", + "V1DeleteFileResponse", + "V1DeleteRecordResponse", + "V1DetokenizeRecordRequest", + "V1DetokenizeRecordResponse", + "V1DetokenizeResponse", + "V1FieldRecords", + "V1FileAvScanStatus", + "V1GetAuthTokenResponse", + "V1GetFileScanStatusResponse", + "V1GetQueryResponse", + "V1InsertRecordResponse", + "V1MemberType", + "V1RecordMetaProperties", + "V1TokenizeRecordRequest", + "V1TokenizeRecordResponse", + "V1TokenizeResponse", + "V1UpdateRecordResponse", + "V1VaultFieldMapping", + "V1VaultSchemaConfig", +] diff --git a/skyflow/generated/rest/types/audit_event_audit_resource_type.py b/skyflow/generated/rest/types/audit_event_audit_resource_type.py new file mode 100644 index 00000000..b6c6aa0c --- /dev/null +++ b/skyflow/generated/rest/types/audit_event_audit_resource_type.py @@ -0,0 +1,39 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +AuditEventAuditResourceType = typing.Union[ + typing.Literal[ + "NONE_API", + "ACCOUNT", + "AUDIT", + "BASE_DATA_TYPE", + "FIELD_TEMPLATE", + "FILE", + "KEY", + "POLICY", + "PROTO_PARSE", + "RECORD", + "ROLE", + "RULE", + "SECRET", + "SERVICE_ACCOUNT", + "TOKEN", + "USER", + "VAULT", + "VAULT_TEMPLATE", + "WORKSPACE", + "TABLE", + "POLICY_TEMPLATE", + "MEMBER", + "TAG", + "CONNECTION", + "MIGRATION", + "SCHEDULED_JOB", + "JOB", + "COLUMN_NAME", + "NETWORK_TOKEN", + "SUBSCRIPTION", + ], + typing.Any, +] diff --git a/skyflow/generated/rest/types/audit_event_context.py b/skyflow/generated/rest/types/audit_event_context.py new file mode 100644 index 00000000..178137ec --- /dev/null +++ b/skyflow/generated/rest/types/audit_event_context.py @@ -0,0 +1,90 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing_extensions +import typing +from ..core.serialization import FieldMetadata +import pydantic +from .v_1_member_type import V1MemberType +from .context_access_type import ContextAccessType +from .context_auth_mode import ContextAuthMode +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class AuditEventContext(UniversalBaseModel): + """ + Context for an audit event. + """ + + change_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="changeID")] = pydantic.Field( + default=None + ) + """ + ID for the audit event. + """ + + request_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="requestID")] = pydantic.Field( + default=None + ) + """ + ID for the request that caused the event. + """ + + trace_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="traceID")] = pydantic.Field( + default=None + ) + """ + ID for the request set by the service that received the request. + """ + + session_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="sessionID")] = pydantic.Field( + default=None + ) + """ + ID for the session in which the request was sent. + """ + + actor: typing.Optional[str] = pydantic.Field(default=None) + """ + Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. + """ + + actor_type: typing_extensions.Annotated[typing.Optional[V1MemberType], FieldMetadata(alias="actorType")] = None + access_type: typing_extensions.Annotated[typing.Optional[ContextAccessType], FieldMetadata(alias="accessType")] = ( + None + ) + ip_address: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="ipAddress")] = pydantic.Field( + default=None + ) + """ + IP Address of the client that made the request. + """ + + origin: typing.Optional[str] = pydantic.Field(default=None) + """ + HTTP Origin request header (including scheme, hostname, and port) of the request. + """ + + auth_mode: typing_extensions.Annotated[typing.Optional[ContextAuthMode], FieldMetadata(alias="authMode")] = None + jwt_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="jwtID")] = pydantic.Field( + default=None + ) + """ + ID of the JWT token. + """ + + bearer_token_context_id: typing_extensions.Annotated[ + typing.Optional[str], FieldMetadata(alias="bearerTokenContextID") + ] = pydantic.Field(default=None) + """ + Embedded User Context. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/audit_event_data.py b/skyflow/generated/rest/types/audit_event_data.py new file mode 100644 index 00000000..78385d17 --- /dev/null +++ b/skyflow/generated/rest/types/audit_event_data.py @@ -0,0 +1,26 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class AuditEventData(UniversalBaseModel): + """ + Any Sensitive data that needs to be wrapped. + """ + + content: typing.Optional[str] = pydantic.Field(default=None) + """ + The entire body of the data requested or the query fired. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/audit_event_http_info.py b/skyflow/generated/rest/types/audit_event_http_info.py new file mode 100644 index 00000000..14df874b --- /dev/null +++ b/skyflow/generated/rest/types/audit_event_http_info.py @@ -0,0 +1,29 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing_extensions +import typing +from ..core.serialization import FieldMetadata +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class AuditEventHttpInfo(UniversalBaseModel): + uri: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="URI")] = pydantic.Field(default=None) + """ + The http URI that is used. + """ + + method: typing.Optional[str] = pydantic.Field(default=None) + """ + http method used. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/batch_record_method.py b/skyflow/generated/rest/types/batch_record_method.py new file mode 100644 index 00000000..e1882ba5 --- /dev/null +++ b/skyflow/generated/rest/types/batch_record_method.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +BatchRecordMethod = typing.Union[typing.Literal["NONE", "POST", "PUT", "GET", "DELETE"], typing.Any] diff --git a/skyflow/generated/rest/types/context_access_type.py b/skyflow/generated/rest/types/context_access_type.py new file mode 100644 index 00000000..056a10f4 --- /dev/null +++ b/skyflow/generated/rest/types/context_access_type.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ContextAccessType = typing.Union[typing.Literal["ACCESS_NONE", "API", "SQL"], typing.Any] diff --git a/skyflow/generated/rest/types/context_auth_mode.py b/skyflow/generated/rest/types/context_auth_mode.py new file mode 100644 index 00000000..ad630625 --- /dev/null +++ b/skyflow/generated/rest/types/context_auth_mode.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ContextAuthMode = typing.Union[typing.Literal["AUTH_NONE", "OKTA_JWT", "SERVICE_ACCOUNT_JWT", "PAT_JWT"], typing.Any] diff --git a/skyflow/generated/rest/types/detokenize_record_response_value_type.py b/skyflow/generated/rest/types/detokenize_record_response_value_type.py new file mode 100644 index 00000000..3703064a --- /dev/null +++ b/skyflow/generated/rest/types/detokenize_record_response_value_type.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +DetokenizeRecordResponseValueType = typing.Union[ + typing.Literal["NONE", "STRING", "INTEGER", "FLOAT", "BOOL", "DATETIME", "JSON", "ARRAY", "DATE"], typing.Any +] diff --git a/skyflow/generated/rest/types/googlerpc_status.py b/skyflow/generated/rest/types/googlerpc_status.py new file mode 100644 index 00000000..aceede7e --- /dev/null +++ b/skyflow/generated/rest/types/googlerpc_status.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .protobuf_any import ProtobufAny +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic + + +class GooglerpcStatus(UniversalBaseModel): + code: typing.Optional[int] = None + message: typing.Optional[str] = None + details: typing.Optional[typing.List[ProtobufAny]] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/protobuf_any.py b/skyflow/generated/rest/types/protobuf_any.py new file mode 100644 index 00000000..9d141254 --- /dev/null +++ b/skyflow/generated/rest/types/protobuf_any.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing_extensions +import typing +from ..core.serialization import FieldMetadata +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic + + +class ProtobufAny(UniversalBaseModel): + type: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="@type")] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/redaction_enum_redaction.py b/skyflow/generated/rest/types/redaction_enum_redaction.py new file mode 100644 index 00000000..25529a7d --- /dev/null +++ b/skyflow/generated/rest/types/redaction_enum_redaction.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +RedactionEnumRedaction = typing.Union[typing.Literal["DEFAULT", "REDACTED", "MASKED", "PLAIN_TEXT"], typing.Any] diff --git a/skyflow/generated/rest/types/request_action_type.py b/skyflow/generated/rest/types/request_action_type.py new file mode 100644 index 00000000..c10fe1ce --- /dev/null +++ b/skyflow/generated/rest/types/request_action_type.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +RequestActionType = typing.Union[ + typing.Literal[ + "NONE", + "ASSIGN", + "CREATE", + "DELETE", + "EXECUTE", + "LIST", + "READ", + "UNASSIGN", + "UPDATE", + "VALIDATE", + "LOGIN", + "ROTATE", + "SCHEDULEROTATION", + "SCHEDULEROTATIONALERT", + "IMPORT", + "GETIMPORTPARAMETERS", + "PING", + "GETCLOUDPROVIDER", + ], + typing.Any, +] diff --git a/skyflow/generated/rest/types/v_1_audit_after_options.py b/skyflow/generated/rest/types/v_1_audit_after_options.py new file mode 100644 index 00000000..0f078667 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_audit_after_options.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +import typing_extensions +from ..core.serialization import FieldMetadata +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1AuditAfterOptions(UniversalBaseModel): + timestamp: typing.Optional[str] = pydantic.Field(default=None) + """ + Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + """ + + change_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="changeID")] = pydantic.Field( + default=None + ) + """ + Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_audit_event_response.py b/skyflow/generated/rest/types/v_1_audit_event_response.py new file mode 100644 index 00000000..2ff30533 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_audit_event_response.py @@ -0,0 +1,38 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from .audit_event_data import AuditEventData +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1AuditEventResponse(UniversalBaseModel): + """ + Contains fields for defining Response Properties. + """ + + code: typing.Optional[int] = pydantic.Field(default=None) + """ + The status of the overall operation. + """ + + message: typing.Optional[str] = pydantic.Field(default=None) + """ + The status message for the overall operation. + """ + + data: typing.Optional[AuditEventData] = None + timestamp: typing.Optional[str] = pydantic.Field(default=None) + """ + time when this response is generated, use extention method to set it. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_audit_response.py b/skyflow/generated/rest/types/v_1_audit_response.py new file mode 100644 index 00000000..617c1fd9 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_audit_response.py @@ -0,0 +1,28 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_audit_response_event import V1AuditResponseEvent +import pydantic +import typing_extensions +from .v_1_audit_after_options import V1AuditAfterOptions +from ..core.serialization import FieldMetadata +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1AuditResponse(UniversalBaseModel): + event: typing.Optional[typing.List[V1AuditResponseEvent]] = pydantic.Field(default=None) + """ + Events matching the query. + """ + + next_ops: typing_extensions.Annotated[typing.Optional[V1AuditAfterOptions], FieldMetadata(alias="nextOps")] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_audit_response_event.py b/skyflow/generated/rest/types/v_1_audit_response_event.py new file mode 100644 index 00000000..b623257e --- /dev/null +++ b/skyflow/generated/rest/types/v_1_audit_response_event.py @@ -0,0 +1,50 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .audit_event_context import AuditEventContext +from .v_1_audit_response_event_request import V1AuditResponseEventRequest +from .v_1_audit_event_response import V1AuditEventResponse +import typing_extensions +from ..core.serialization import FieldMetadata +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1AuditResponseEvent(UniversalBaseModel): + """ + Audit event details. + """ + + context: typing.Optional[AuditEventContext] = None + request: typing.Optional[V1AuditResponseEventRequest] = None + response: typing.Optional[V1AuditEventResponse] = None + parent_account_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="parentAccountID")] = ( + pydantic.Field(default=None) + ) + """ + Parent account ID of the account that made the request, if any. + """ + + account_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="accountID")] = pydantic.Field( + default=None + ) + """ + ID of the account that made the request. + """ + + resource_i_ds: typing_extensions.Annotated[ + typing.Optional[typing.List[str]], FieldMetadata(alias="resourceIDs") + ] = pydantic.Field(default=None) + """ + IDs for resources involved in the event. Presented in `{resourceType}/{resourceID}` format. For example, `VAULT/cd1d815aa09b4cbfbb803bd20349f202`. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_audit_response_event_request.py b/skyflow/generated/rest/types/v_1_audit_response_event_request.py new file mode 100644 index 00000000..5eb9a709 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_audit_response_event_request.py @@ -0,0 +1,67 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .audit_event_data import AuditEventData +import typing_extensions +from ..core.serialization import FieldMetadata +import pydantic +from .request_action_type import RequestActionType +from .audit_event_audit_resource_type import AuditEventAuditResourceType +from .audit_event_http_info import AuditEventHttpInfo +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1AuditResponseEventRequest(UniversalBaseModel): + """ + Contains fields for defining Request Properties. + """ + + data: typing.Optional[AuditEventData] = None + api_name: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="apiName")] = pydantic.Field( + default=None + ) + """ + API name. + """ + + workspace_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="workspaceID")] = ( + pydantic.Field(default=None) + ) + """ + The workspaceID (if any) of the request. + """ + + vault_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="vaultID")] = pydantic.Field( + default=None + ) + """ + The vaultID (if any) of the request. + """ + + tags: typing.Optional[typing.List[str]] = pydantic.Field(default=None) + """ + Tags associated with the event. To provide better search capabilities. Like login. + """ + + timestamp: typing.Optional[str] = pydantic.Field(default=None) + """ + time when this request is generated, use extention method to set it. + """ + + action_type: typing_extensions.Annotated[typing.Optional[RequestActionType], FieldMetadata(alias="actionType")] = ( + None + ) + resource_type: typing_extensions.Annotated[ + typing.Optional[AuditEventAuditResourceType], FieldMetadata(alias="resourceType") + ] = None + http_info: typing_extensions.Annotated[typing.Optional[AuditEventHttpInfo], FieldMetadata(alias="httpInfo")] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_batch_operation_response.py b/skyflow/generated/rest/types/v_1_batch_operation_response.py new file mode 100644 index 00000000..72643ce2 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_batch_operation_response.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing_extensions +import typing +from ..core.serialization import FieldMetadata +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1BatchOperationResponse(UniversalBaseModel): + vault_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="vaultID")] = pydantic.Field( + default=None + ) + """ + ID of the vault. + """ + + responses: typing.Optional[typing.List[typing.Dict[str, typing.Optional[typing.Any]]]] = pydantic.Field( + default=None + ) + """ + Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs:
  • `POST` returns an Insert Records response.
  • `PUT` returns an Update Record response.
  • `GET` returns a Get Record response.
  • `DELETE` returns a Delete Record response.
+ """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_batch_record.py b/skyflow/generated/rest/types/v_1_batch_record.py new file mode 100644 index 00000000..7dca5fda --- /dev/null +++ b/skyflow/generated/rest/types/v_1_batch_record.py @@ -0,0 +1,69 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +import typing_extensions +from ..core.serialization import FieldMetadata +from .batch_record_method import BatchRecordMethod +from .redaction_enum_redaction import RedactionEnumRedaction +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1BatchRecord(UniversalBaseModel): + fields: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = pydantic.Field(default=None) + """ + Field and value key pairs. For example, `{'field_1':'value_1', 'field_2':'value_2'}`. Only valid when `method` is `POST` or `PUT`. + """ + + table_name: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="tableName")] = pydantic.Field( + default=None + ) + """ + Name of the table to perform the operation on. + """ + + method: typing.Optional[BatchRecordMethod] = None + batch_id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="batchID")] = pydantic.Field( + default=None + ) + """ + ID to group operations by. Operations in the same group are executed sequentially. + """ + + redaction: typing.Optional[RedactionEnumRedaction] = None + tokenization: typing.Optional[bool] = pydantic.Field(default=None) + """ + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + """ + + id: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="ID")] = pydantic.Field(default=None) + """ + `skyflow_id` for the record. Only valid when `method` is `GET`, `DELETE`, or `PUT`. + """ + + download_url: typing_extensions.Annotated[typing.Optional[bool], FieldMetadata(alias="downloadURL")] = ( + pydantic.Field(default=None) + ) + """ + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + """ + + upsert: typing.Optional[str] = pydantic.Field(default=None) + """ + Column that stores primary keys for upsert operations. The column must be marked as unique in the vault schema. Only valid when `method` is `POST`. + """ + + tokens: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = pydantic.Field(default=None) + """ + Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_bin_list_response.py b/skyflow/generated/rest/types/v_1_bin_list_response.py new file mode 100644 index 00000000..bd4f69b9 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_bin_list_response.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_card import V1Card +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1BinListResponse(UniversalBaseModel): + """ + Response to the Get BIN request. + """ + + cards_data: typing.Optional[typing.List[V1Card]] = pydantic.Field(default=None) + """ + Card metadata associated with the specified BIN. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_bulk_delete_record_response.py b/skyflow/generated/rest/types/v_1_bulk_delete_record_response.py new file mode 100644 index 00000000..6d03bccd --- /dev/null +++ b/skyflow/generated/rest/types/v_1_bulk_delete_record_response.py @@ -0,0 +1,26 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing_extensions +import typing +from ..core.serialization import FieldMetadata +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1BulkDeleteRecordResponse(UniversalBaseModel): + record_id_response: typing_extensions.Annotated[ + typing.Optional[typing.List[str]], FieldMetadata(alias="RecordIDResponse") + ] = pydantic.Field(default=None) + """ + IDs for the deleted records, or `*` if all records were deleted. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_bulk_get_record_response.py b/skyflow/generated/rest/types/v_1_bulk_get_record_response.py new file mode 100644 index 00000000..7244bc7f --- /dev/null +++ b/skyflow/generated/rest/types/v_1_bulk_get_record_response.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_field_records import V1FieldRecords +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1BulkGetRecordResponse(UniversalBaseModel): + records: typing.Optional[typing.List[V1FieldRecords]] = pydantic.Field(default=None) + """ + The specified records. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_byot.py b/skyflow/generated/rest/types/v_1_byot.py new file mode 100644 index 00000000..3c03bdac --- /dev/null +++ b/skyflow/generated/rest/types/v_1_byot.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +V1Byot = typing.Union[typing.Literal["DISABLE", "ENABLE", "ENABLE_STRICT"], typing.Any] diff --git a/skyflow/generated/rest/types/v_1_card.py b/skyflow/generated/rest/types/v_1_card.py new file mode 100644 index 00000000..c5a641b1 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_card.py @@ -0,0 +1,68 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing_extensions +import typing +from ..core.serialization import FieldMetadata +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1Card(UniversalBaseModel): + """ + Card metadata of the requested BIN. + """ + + bin: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="BIN")] = pydantic.Field(default=None) + """ + BIN of the card. + """ + + issuer_name: typing.Optional[str] = pydantic.Field(default=None) + """ + Name of the card issuer bank. + """ + + country_code: typing.Optional[str] = pydantic.Field(default=None) + """ + Country code of the card. + """ + + currency: typing.Optional[str] = pydantic.Field(default=None) + """ + Currency of the card. + """ + + card_type: typing.Optional[str] = pydantic.Field(default=None) + """ + Type of the card. + """ + + card_category: typing.Optional[str] = pydantic.Field(default=None) + """ + Category of the card. + """ + + card_scheme: typing.Optional[str] = pydantic.Field(default=None) + """ + Scheme of the card. + """ + + card_last_four_digits: typing.Optional[str] = pydantic.Field(default=None) + """ + Last four digits of the card number. + """ + + card_expiry: typing.Optional[str] = pydantic.Field(default=None) + """ + Expiry date of the card. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_delete_file_response.py b/skyflow/generated/rest/types/v_1_delete_file_response.py new file mode 100644 index 00000000..6e995cec --- /dev/null +++ b/skyflow/generated/rest/types/v_1_delete_file_response.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1DeleteFileResponse(UniversalBaseModel): + skyflow_id: typing.Optional[str] = pydantic.Field(default=None) + """ + ID of the record. + """ + + deleted: typing.Optional[bool] = pydantic.Field(default=None) + """ + If `true`, the file was deleted. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_delete_record_response.py b/skyflow/generated/rest/types/v_1_delete_record_response.py new file mode 100644 index 00000000..366cb30b --- /dev/null +++ b/skyflow/generated/rest/types/v_1_delete_record_response.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1DeleteRecordResponse(UniversalBaseModel): + skyflow_id: typing.Optional[str] = pydantic.Field(default=None) + """ + ID of the deleted record. + """ + + deleted: typing.Optional[bool] = pydantic.Field(default=None) + """ + If `true`, the record was deleted. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_detokenize_record_request.py b/skyflow/generated/rest/types/v_1_detokenize_record_request.py new file mode 100644 index 00000000..b6e225c3 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_detokenize_record_request.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from .redaction_enum_redaction import RedactionEnumRedaction +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1DetokenizeRecordRequest(UniversalBaseModel): + token: typing.Optional[str] = pydantic.Field(default=None) + """ + Token that identifies the record to detokenize. + """ + + redaction: typing.Optional[RedactionEnumRedaction] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_detokenize_record_response.py b/skyflow/generated/rest/types/v_1_detokenize_record_response.py new file mode 100644 index 00000000..bbc26aa0 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_detokenize_record_response.py @@ -0,0 +1,38 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +import typing_extensions +from .detokenize_record_response_value_type import DetokenizeRecordResponseValueType +from ..core.serialization import FieldMetadata +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1DetokenizeRecordResponse(UniversalBaseModel): + token: typing.Optional[str] = pydantic.Field(default=None) + """ + Token of the record. + """ + + value_type: typing_extensions.Annotated[ + typing.Optional[DetokenizeRecordResponseValueType], FieldMetadata(alias="valueType") + ] = None + value: typing.Optional[str] = pydantic.Field(default=None) + """ + Data corresponding to the token. + """ + + error: typing.Optional[str] = pydantic.Field(default=None) + """ + Error if token isn't found. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_detokenize_response.py b/skyflow/generated/rest/types/v_1_detokenize_response.py new file mode 100644 index 00000000..63e97c84 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_detokenize_response.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_detokenize_record_response import V1DetokenizeRecordResponse +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1DetokenizeResponse(UniversalBaseModel): + records: typing.Optional[typing.List[V1DetokenizeRecordResponse]] = pydantic.Field(default=None) + """ + Records corresponding to the specified tokens. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_field_records.py b/skyflow/generated/rest/types/v_1_field_records.py new file mode 100644 index 00000000..07a8bf58 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_field_records.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1FieldRecords(UniversalBaseModel): + """ + Record values and tokens. + """ + + fields: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = pydantic.Field(default=None) + """ + Fields and values for the record. For example, `{'field_1':'value_1', 'field_2':'value_2'}`. + """ + + tokens: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = pydantic.Field(default=None) + """ + Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_file_av_scan_status.py b/skyflow/generated/rest/types/v_1_file_av_scan_status.py new file mode 100644 index 00000000..78712507 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_file_av_scan_status.py @@ -0,0 +1,18 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +V1FileAvScanStatus = typing.Union[ + typing.Literal[ + "SCAN_NONE", + "SCAN_CLEAN", + "SCAN_INFECTED", + "SCAN_DELETED", + "SCAN_ERROR", + "SCAN_PENDING", + "SCAN_UNSCANNABLE", + "SCAN_FILE_NOT_FOUND", + "SCAN_INVALID", + ], + typing.Any, +] diff --git a/skyflow/generated/rest/types/v_1_get_auth_token_response.py b/skyflow/generated/rest/types/v_1_get_auth_token_response.py new file mode 100644 index 00000000..d414ed7c --- /dev/null +++ b/skyflow/generated/rest/types/v_1_get_auth_token_response.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing_extensions +import typing +from ..core.serialization import FieldMetadata +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1GetAuthTokenResponse(UniversalBaseModel): + access_token: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="accessToken")] = ( + pydantic.Field(default=None) + ) + """ + AccessToken. + """ + + token_type: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="tokenType")] = pydantic.Field( + default=None + ) + """ + TokenType : Bearer. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_get_file_scan_status_response.py b/skyflow/generated/rest/types/v_1_get_file_scan_status_response.py new file mode 100644 index 00000000..71349961 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_get_file_scan_status_response.py @@ -0,0 +1,20 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_file_av_scan_status import V1FileAvScanStatus +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic + + +class V1GetFileScanStatusResponse(UniversalBaseModel): + av_scan_status: typing.Optional[V1FileAvScanStatus] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_get_query_response.py b/skyflow/generated/rest/types/v_1_get_query_response.py new file mode 100644 index 00000000..778a517a --- /dev/null +++ b/skyflow/generated/rest/types/v_1_get_query_response.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_field_records import V1FieldRecords +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1GetQueryResponse(UniversalBaseModel): + records: typing.Optional[typing.List[V1FieldRecords]] = pydantic.Field(default=None) + """ + Records returned by the query. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_insert_record_response.py b/skyflow/generated/rest/types/v_1_insert_record_response.py new file mode 100644 index 00000000..a3344c92 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_insert_record_response.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_record_meta_properties import V1RecordMetaProperties +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1InsertRecordResponse(UniversalBaseModel): + records: typing.Optional[typing.List[V1RecordMetaProperties]] = pydantic.Field(default=None) + """ + Identifiers for the inserted records. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_member_type.py b/skyflow/generated/rest/types/v_1_member_type.py new file mode 100644 index 00000000..4f862413 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_member_type.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +V1MemberType = typing.Union[typing.Literal["NONE", "USER", "SERVICE_ACCOUNT"], typing.Any] diff --git a/skyflow/generated/rest/types/v_1_record_meta_properties.py b/skyflow/generated/rest/types/v_1_record_meta_properties.py new file mode 100644 index 00000000..a4eb95b7 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_record_meta_properties.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1RecordMetaProperties(UniversalBaseModel): + skyflow_id: typing.Optional[str] = pydantic.Field(default=None) + """ + ID of the inserted record. + """ + + tokens: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = pydantic.Field(default=None) + """ + Tokens for the record. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_tokenize_record_request.py b/skyflow/generated/rest/types/v_1_tokenize_record_request.py new file mode 100644 index 00000000..9fba53a2 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_tokenize_record_request.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +import typing_extensions +from ..core.serialization import FieldMetadata +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1TokenizeRecordRequest(UniversalBaseModel): + value: typing.Optional[str] = pydantic.Field(default=None) + """ + Existing value to return a token for. + """ + + column_group: typing_extensions.Annotated[typing.Optional[str], FieldMetadata(alias="columnGroup")] = ( + pydantic.Field(default=None) + ) + """ + Name of the column group that the value belongs to. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_tokenize_record_response.py b/skyflow/generated/rest/types/v_1_tokenize_record_response.py new file mode 100644 index 00000000..c105e9fc --- /dev/null +++ b/skyflow/generated/rest/types/v_1_tokenize_record_response.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1TokenizeRecordResponse(UniversalBaseModel): + token: typing.Optional[str] = pydantic.Field(default=None) + """ + Token corresponding to a value. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_tokenize_response.py b/skyflow/generated/rest/types/v_1_tokenize_response.py new file mode 100644 index 00000000..0e1886b4 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_tokenize_response.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +from .v_1_tokenize_record_response import V1TokenizeRecordResponse +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1TokenizeResponse(UniversalBaseModel): + records: typing.Optional[typing.List[V1TokenizeRecordResponse]] = pydantic.Field(default=None) + """ + Tokens corresponding to the specified values. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_update_record_response.py b/skyflow/generated/rest/types/v_1_update_record_response.py new file mode 100644 index 00000000..be6da8fb --- /dev/null +++ b/skyflow/generated/rest/types/v_1_update_record_response.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1UpdateRecordResponse(UniversalBaseModel): + skyflow_id: typing.Optional[str] = pydantic.Field(default=None) + """ + ID of the updated record. + """ + + tokens: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = pydantic.Field(default=None) + """ + Tokens for the record. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_vault_field_mapping.py b/skyflow/generated/rest/types/v_1_vault_field_mapping.py new file mode 100644 index 00000000..a567d639 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_vault_field_mapping.py @@ -0,0 +1,36 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1VaultFieldMapping(UniversalBaseModel): + """ + Mapping of the fields in the vault to the fields to use for the lookup. + """ + + card_number: typing.Optional[str] = pydantic.Field(default=None) + """ + Name of the column that stores the card number. + """ + + card_last_four_digits: typing.Optional[str] = pydantic.Field(default=None) + """ + Name of the column that stores the card number suffix. + """ + + card_expiry: typing.Optional[str] = pydantic.Field(default=None) + """ + Name of the column that stores the expiry date. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/types/v_1_vault_schema_config.py b/skyflow/generated/rest/types/v_1_vault_schema_config.py new file mode 100644 index 00000000..a3f3f0b6 --- /dev/null +++ b/skyflow/generated/rest/types/v_1_vault_schema_config.py @@ -0,0 +1,34 @@ +# This file was auto-generated by Fern from our API Definition. + +from ..core.pydantic_utilities import UniversalBaseModel +import typing +import pydantic +from .v_1_vault_field_mapping import V1VaultFieldMapping +from ..core.pydantic_utilities import IS_PYDANTIC_V2 + + +class V1VaultSchemaConfig(UniversalBaseModel): + """ + Details of the vault that stores additional card details. + """ + + id: typing.Optional[str] = pydantic.Field(default=None) + """ + ID of the vault that stores card details. + """ + + table_name: typing.Optional[str] = pydantic.Field(default=None) + """ + Name of the table that stores card details. + """ + + mapping: typing.Optional[V1VaultFieldMapping] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/skyflow/generated/rest/version.py b/skyflow/generated/rest/version.py new file mode 100644 index 00000000..f8d02ff4 --- /dev/null +++ b/skyflow/generated/rest/version.py @@ -0,0 +1 @@ +__version__ = '2.0.0b1.dev0+3d4ee51' diff --git a/skyflow/service_account/_utils.py b/skyflow/service_account/_utils.py index 78617670..715716d8 100644 --- a/skyflow/service_account/_utils.py +++ b/skyflow/service_account/_utils.py @@ -3,7 +3,6 @@ import time import jwt from skyflow.error import SkyflowError -from skyflow.generated.rest.models import V1GetAuthTokenRequest from skyflow.service_account.client.auth_client import AuthClient from skyflow.utils.logger import log_info, log_error_log from skyflow.utils import get_base_url, format_scope, SkyflowMessages @@ -89,10 +88,9 @@ def get_service_account_token(credentials, options, logger): if options and "role_ids" in options: formatted_scope = format_scope(options.get("role_ids")) - request = V1GetAuthTokenRequest(assertion = signed_token, + response = auth_api.authentication_service_get_auth_token(assertion = signed_token, grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer", scope=formatted_scope) - response = auth_api.authentication_service_get_auth_token(request) log_info(SkyflowMessages.Info.GET_BEARER_TOKEN_SUCCESS.value, logger) return response.access_token, response.token_type diff --git a/skyflow/service_account/client/auth_client.py b/skyflow/service_account/client/auth_client.py index c1cc9cb2..948e05f3 100644 --- a/skyflow/service_account/client/auth_client.py +++ b/skyflow/service_account/client/auth_client.py @@ -1,18 +1,13 @@ -from skyflow.generated.rest import Configuration, ApiClient -from skyflow.generated.rest.api import AuthenticationApi - +from skyflow.generated.rest.client import Skyflow +from skyflow.utils.constants import OPTIONAL_TOKEN class AuthClient: def __init__(self, url): self.__url = url - self.__client_configuration = self.initialize_client_configuration() self.__api_client = self.initialize_api_client() - def initialize_client_configuration(self): - return Configuration(host=self.__url) - def initialize_api_client(self): - return ApiClient(self.__client_configuration) + return Skyflow(base_url=self.__url, token=OPTIONAL_TOKEN) def get_auth_api(self): - return AuthenticationApi(self.__api_client) \ No newline at end of file + return self.__api_client.authentication \ No newline at end of file diff --git a/skyflow/utils/_utils.py b/skyflow/utils/_utils.py index 2261d3e6..8f035e93 100644 --- a/skyflow/utils/_utils.py +++ b/skyflow/utils/_utils.py @@ -13,8 +13,9 @@ from skyflow.error import SkyflowError from skyflow.generated.rest import V1UpdateRecordResponse, V1BulkDeleteRecordResponse, \ V1DetokenizeResponse, V1TokenizeResponse, V1GetQueryResponse, V1BulkGetRecordResponse -from skyflow.utils.logger import log_error, log_error_log +from skyflow.utils.logger import log_error_log from . import SkyflowMessages, SDK_VERSION +from .constants import PROTOCOL from .enums import Env, ContentType, EnvUrls from skyflow.vault.data import InsertResponse, UpdateResponse, DeleteResponse, QueryResponse, GetResponse from .validations import validate_invoke_connection_params @@ -61,7 +62,7 @@ def get_vault_url(cluster_id, env,vault_id, logger = None): raise SkyflowError(SkyflowMessages.Error.INVALID_ENV.value.format(vault_id), invalid_input_error_code) base_url = EnvUrls[env.name].value - protocol = "https" if env != Env.PROD else "http" + protocol = PROTOCOL return f"{protocol}://{cluster_id}.{base_url}" diff --git a/skyflow/utils/constants.py b/skyflow/utils/constants.py new file mode 100644 index 00000000..fea57008 --- /dev/null +++ b/skyflow/utils/constants.py @@ -0,0 +1,2 @@ +OPTIONAL_TOKEN='token' +PROTOCOL='https' \ No newline at end of file diff --git a/skyflow/utils/enums/env.py b/skyflow/utils/enums/env.py index 862f8f8a..1f2f7f17 100644 --- a/skyflow/utils/enums/env.py +++ b/skyflow/utils/enums/env.py @@ -1,13 +1,13 @@ from enum import Enum class Env(Enum): - DEV = 'DEV', - SANDBOX = 'SANDBOX', + DEV = 'DEV' + SANDBOX = 'SANDBOX' PROD = 'PROD' STAGE = 'STAGE' class EnvUrls(Enum): - PROD = "vault.skyflowapis.com", - SANDBOX = "vault.skyflowapis-preview.com", + PROD = "vault.skyflowapis.com" + SANDBOX = "vault.skyflowapis-preview.com" DEV = "vault.skyflowapis.dev" STAGE = "vault.skyflowapis.tech" \ No newline at end of file diff --git a/skyflow/utils/enums/redaction_type.py b/skyflow/utils/enums/redaction_type.py index 85310048..1780e820 100644 --- a/skyflow/utils/enums/redaction_type.py +++ b/skyflow/utils/enums/redaction_type.py @@ -1,8 +1,7 @@ from enum import Enum -from skyflow.generated.rest import RedactionEnumREDACTION class RedactionType(Enum): - PLAIN_TEXT = RedactionEnumREDACTION.PLAIN_TEXT - MASKED = RedactionEnumREDACTION.MASKED - DEFAULT = RedactionEnumREDACTION.DEFAULT - REDACTED = RedactionEnumREDACTION.REDACTED + PLAIN_TEXT = 'PLAIN_TEXT' + MASKED = 'MASKED' + DEFAULT = 'DEFAULT' + REDACTED = 'REDACTED' diff --git a/skyflow/utils/enums/token_mode.py b/skyflow/utils/enums/token_mode.py index 650f9a96..a073b125 100644 --- a/skyflow/utils/enums/token_mode.py +++ b/skyflow/utils/enums/token_mode.py @@ -1,7 +1,6 @@ from enum import Enum -from skyflow.generated.rest import V1BYOT class TokenMode(Enum): - DISABLE = V1BYOT.DISABLE - ENABLE = V1BYOT.ENABLE - ENABLE_STRICT = V1BYOT.ENABLE_STRICT \ No newline at end of file + DISABLE = "DISABLE" + ENABLE = "ENABLE" + ENABLE_STRICT = "ENABLE_STRICT" \ No newline at end of file diff --git a/skyflow/utils/validations/_validations.py b/skyflow/utils/validations/_validations.py index 5b7827a9..93d10468 100644 --- a/skyflow/utils/validations/_validations.py +++ b/skyflow/utils/validations/_validations.py @@ -514,16 +514,20 @@ def validate_detokenize_request(logger, request): raise SkyflowError(SkyflowMessages.Error.EMPTY_TOKENS_LIST_VALUE.value, invalid_input_error_code) for item in request.data: - if 'token' not in item or 'redaction' not in item: - raise SkyflowError(SkyflowMessages.Error.INVALID_TOKENS_LIST_VALUE.value(type(request.data)), invalid_input_error_code) + if 'token' not in item: + raise SkyflowError(SkyflowMessages.Error.INVALID_TOKENS_LIST_VALUE.value.format(type(request.data)), + invalid_input_error_code) + token = item.get('token') - redaction = item.get('redaction') + redaction = item.get('redaction', None) if not isinstance(token, str) or not token: - raise SkyflowError(SkyflowMessages.Error.INVALID_TOKEN_TYPE.value.format("DETOKENIZE"), invalid_input_error_code) + raise SkyflowError(SkyflowMessages.Error.INVALID_TOKEN_TYPE.value.format("DETOKENIZE"), + invalid_input_error_code) - if not isinstance(redaction, RedactionType) or not redaction: - raise SkyflowError(SkyflowMessages.Error.INVALID_REDACTION_TYPE.value.format(type(redaction)), invalid_input_error_code) + if redaction is not None and not isinstance(redaction, RedactionType): + raise SkyflowError(SkyflowMessages.Error.INVALID_REDACTION_TYPE.value.format(type(redaction)), + invalid_input_error_code) def validate_tokenize_request(logger, request): parameters = request.values diff --git a/skyflow/vault/client/client.py b/skyflow/vault/client/client.py index 34a9374a..e3e543ae 100644 --- a/skyflow/vault/client/client.py +++ b/skyflow/vault/client/client.py @@ -1,5 +1,4 @@ -import json -from skyflow.generated.rest import Configuration, RecordsApi, ApiClient, TokensApi, QueryApi +from skyflow.generated.rest.client import Skyflow from skyflow.service_account import generate_bearer_token, generate_bearer_token_from_creds, is_expired from skyflow.utils import get_vault_url, get_credentials, SkyflowMessages from skyflow.utils.logger import log_info @@ -30,20 +29,19 @@ def initialize_client_configuration(self): self.__config.get("env"), self.__config.get("vault_id"), logger = self.__logger) - self.__client_configuration = Configuration(host=vault_url, access_token=token) - self.initialize_api_client(self.__client_configuration) + self.initialize_api_client(vault_url, token) - def initialize_api_client(self, config): - self.__api_client = ApiClient(config) + def initialize_api_client(self, vault_url, token): + self.__api_client = Skyflow(base_url=vault_url, token=token) def get_records_api(self): - return RecordsApi(self.__api_client) + return self.__api_client.records def get_tokens_api(self): - return TokensApi(self.__api_client) + return self.__api_client.tokens def get_query_api(self): - return QueryApi(self.__api_client) + return self.__api_client.query def get_vault_id(self): return self.__config.get("vault_id") diff --git a/skyflow/vault/controller/_vault.py b/skyflow/vault/controller/_vault.py index 9867443f..cabd82db 100644 --- a/skyflow/vault/controller/_vault.py +++ b/skyflow/vault/controller/_vault.py @@ -1,11 +1,9 @@ -from skyflow.generated.rest import V1FieldRecords, RecordServiceInsertRecordBody, V1DetokenizeRecordRequest, \ - V1DetokenizePayload, V1TokenizeRecordRequest, V1TokenizePayload, QueryServiceExecuteQueryBody, \ - RecordServiceBulkDeleteRecordBody, RecordServiceUpdateRecordBody, RecordServiceBatchOperationBody, V1BatchRecord, \ - BatchRecordMethod -from skyflow.generated.rest.exceptions import BadRequestException, UnauthorizedException, ForbiddenException +from skyflow.generated.rest import V1FieldRecords, V1BatchRecord, V1TokenizeRecordRequest, \ + V1DetokenizeRecordRequest from skyflow.utils import SkyflowMessages, parse_insert_response, \ handle_exception, parse_update_record_response, parse_delete_response, parse_detokenize_response, \ parse_tokenize_response, parse_query_response, parse_get_response, encode_column_values +from skyflow.utils.enums import RequestMethod from skyflow.utils.logger import log_info, log_error_log from skyflow.utils.validations import validate_insert_request, validate_delete_request, validate_query_request, \ validate_get_request, validate_update_request, validate_detokenize_request, validate_tokenize_request @@ -30,8 +28,6 @@ def __build_bulk_field_records(self, values, tokens=None): fields=value, tokens=token ) - if token is not None: - bulk_record.tokens = token bulk_record_list.append(bulk_record) return bulk_record_list @@ -42,7 +38,7 @@ def __build_batch_field_records(self, values, tokens, table_name, return_tokens, batch_record = V1BatchRecord( fields=value, table_name=table_name, - method=BatchRecordMethod.POST, + method=RequestMethod.POST.value, tokenization=return_tokens, upsert=upsert, tokens=token @@ -61,21 +57,11 @@ def __build_insert_body(self, request: InsertRequest): request.return_tokens, request.upsert ) - body = RecordServiceBatchOperationBody( - records=records_list, - continue_on_error=request.continue_on_error, - byot=request.token_mode.value - ) - return body + + return records_list else: records_list = self.__build_bulk_field_records(request.values, request.tokens) - return RecordServiceInsertRecordBody( - records=records_list, - tokenization=request.return_tokens, - upsert=request.upsert, - homogeneous=request.homogeneous, - byot=request.token_mode.value - ) + return records_list def insert(self, request: InsertRequest): log_info(SkyflowMessages.Info.VALIDATE_INSERT_REQUEST.value, self.__vault_client.get_logger()) @@ -87,26 +73,21 @@ def insert(self, request: InsertRequest): try: log_info(SkyflowMessages.Info.INSERT_TRIGGERED.value, self.__vault_client.get_logger()) - if request.continue_on_error: api_response = records_api.record_service_batch_operation(self.__vault_client.get_vault_id(), - insert_body) + records=insert_body, continue_on_error=request.continue_on_error, byot=request.token_mode.value) else: api_response = records_api.record_service_insert_record(self.__vault_client.get_vault_id(), - request.table_name, insert_body) + request.table_name, records=insert_body,tokenization= request.return_tokens, upsert=request.upsert, homogeneous=request.homogeneous, byot=request.token_mode.value) insert_response = parse_insert_response(api_response, request.continue_on_error) log_info(SkyflowMessages.Info.INSERT_SUCCESS.value, self.__vault_client.get_logger()) return insert_response - except BadRequestException as e: + except Exception as e: log_error_log(SkyflowMessages.ErrorLogs.INSERT_RECORDS_REJECTED.value, self.__vault_client.get_logger()) handle_exception(e, self.__vault_client.get_logger()) - except UnauthorizedException as e: - handle_exception(e, self.__vault_client.get_logger()) - except ForbiddenException as e: - handle_exception(e, self.__vault_client.get_logger()) def update(self, request: UpdateRequest): log_info(SkyflowMessages.Info.VALIDATE_UPDATE_REQUEST.value, self.__vault_client.get_logger()) @@ -115,7 +96,6 @@ def update(self, request: UpdateRequest): self.__initialize() field = {key: value for key, value in request.data.items() if key != "skyflow_id"} record = V1FieldRecords(fields=field, tokens = request.tokens) - payload = RecordServiceUpdateRecordBody(record=record, tokenization=request.return_tokens, byot=request.token_mode.value) records_api = self.__vault_client.get_records_api() try: @@ -123,8 +103,10 @@ def update(self, request: UpdateRequest): api_response = records_api.record_service_update_record( self.__vault_client.get_vault_id(), request.table, - request.data.get("skyflow_id"), - payload + id=request.data.get("skyflow_id"), + record=record, + tokenization=request.return_tokens, + byot=request.token_mode.value ) log_info(SkyflowMessages.Info.UPDATE_SUCCESS.value, self.__vault_client.get_logger()) update_response = parse_update_record_response(api_response) @@ -132,24 +114,19 @@ def update(self, request: UpdateRequest): except Exception as e: log_error_log(SkyflowMessages.ErrorLogs.UPDATE_REQUEST_REJECTED.value, logger = self.__vault_client.get_logger()) handle_exception(e, self.__vault_client.get_logger()) - except UnauthorizedException as e: - handle_exception(e, self.__vault_client.get_logger()) - except ForbiddenException as e: - handle_exception(e, self.__vault_client.get_logger()) def delete(self, request: DeleteRequest): log_info(SkyflowMessages.Info.VALIDATING_DELETE_REQUEST.value, self.__vault_client.get_logger()) validate_delete_request(self.__vault_client.get_logger(), request) log_info(SkyflowMessages.Info.DELETE_REQUEST_RESOLVED.value, self.__vault_client.get_logger()) self.__initialize() - payload = RecordServiceBulkDeleteRecordBody(skyflow_ids=request.ids) records_api = self.__vault_client.get_records_api() try: log_info(SkyflowMessages.Info.DELETE_TRIGGERED.value, self.__vault_client.get_logger()) api_response = records_api.record_service_bulk_delete_record( self.__vault_client.get_vault_id(), request.table, - payload + skyflow_ids=request.ids ) log_info(SkyflowMessages.Info.DELETE_SUCCESS.value, self.__vault_client.get_logger()) delete_response = parse_delete_response(api_response) @@ -157,12 +134,6 @@ def delete(self, request: DeleteRequest): except Exception as e: log_error_log(SkyflowMessages.ErrorLogs.DELETE_REQUEST_REJECTED.value, logger = self.__vault_client.get_logger()) handle_exception(e, self.__vault_client.get_logger()) - except UnauthorizedException as e: - log_error_log(SkyflowMessages.ErrorLogs.DELETE_REQUEST_REJECTED.value, - logger=self.__vault_client.get_logger()) - handle_exception(e, self.__vault_client.get_logger()) - except ForbiddenException as e: - handle_exception(e, self.__vault_client.get_logger()) def get(self, request: GetRequest): log_info(SkyflowMessages.Info.VALIDATE_GET_REQUEST.value, self.__vault_client.get_logger()) @@ -193,24 +164,18 @@ def get(self, request: GetRequest): except Exception as e: log_error_log(SkyflowMessages.ErrorLogs.GET_REQUEST_REJECTED.value, self.__vault_client.get_logger()) handle_exception(e, self.__vault_client.get_logger()) - except UnauthorizedException as e: - log_error_log(SkyflowMessages.ErrorLogs.GET_REQUEST_REJECTED.value, self.__vault_client.get_logger()) - handle_exception(e, self.__vault_client.get_logger()) - except ForbiddenException as e: - handle_exception(e, self.__vault_client.get_logger()) def query(self, request: QueryRequest): log_info(SkyflowMessages.Info.VALIDATING_QUERY_REQUEST.value, self.__vault_client.get_logger()) validate_query_request(self.__vault_client.get_logger(), request) log_info(SkyflowMessages.Info.QUERY_REQUEST_RESOLVED.value, self.__vault_client.get_logger()) self.__initialize() - payload = QueryServiceExecuteQueryBody(query=request.query) query_api = self.__vault_client.get_query_api() try: log_info(SkyflowMessages.Info.QUERY_TRIGGERED.value, self.__vault_client.get_logger()) api_response = query_api.query_service_execute_query( self.__vault_client.get_vault_id(), - payload + query=request.query ) log_info(SkyflowMessages.Info.QUERY_SUCCESS.value, self.__vault_client.get_logger()) query_response = parse_query_response(api_response) @@ -218,11 +183,6 @@ def query(self, request: QueryRequest): except Exception as e: log_error_log(SkyflowMessages.ErrorLogs.QUERY_REQUEST_REJECTED.value, self.__vault_client.get_logger()) handle_exception(e, self.__vault_client.get_logger()) - except UnauthorizedException as e: - log_error_log(SkyflowMessages.ErrorLogs.QUERY_REQUEST_REJECTED.value, self.__vault_client.get_logger()) - handle_exception(e, self.__vault_client.get_logger()) - except ForbiddenException as e: - handle_exception(e, self.__vault_client.get_logger()) def detokenize(self, request: DetokenizeRequest): log_info(SkyflowMessages.Info.VALIDATE_DETOKENIZE_REQUEST.value, self.__vault_client.get_logger()) @@ -230,16 +190,19 @@ def detokenize(self, request: DetokenizeRequest): log_info(SkyflowMessages.Info.DETOKENIZE_REQUEST_RESOLVED.value, self.__vault_client.get_logger()) self.__initialize() tokens_list = [ - V1DetokenizeRecordRequest(token=item.get('token'), redaction=item.get('redaction').value) + V1DetokenizeRecordRequest( + token=item.get('token'), + redaction=item.get('redaction', None) + ) for item in request.data ] - payload = V1DetokenizePayload(detokenization_parameters=tokens_list, continue_on_error=request.continue_on_error) tokens_api = self.__vault_client.get_tokens_api() try: log_info(SkyflowMessages.Info.DETOKENIZE_TRIGGERED.value, self.__vault_client.get_logger()) api_response = tokens_api.record_service_detokenize( self.__vault_client.get_vault_id(), - detokenize_payload=payload + detokenization_parameters=tokens_list, + continue_on_error = request.continue_on_error ) log_info(SkyflowMessages.Info.DETOKENIZE_SUCCESS.value, self.__vault_client.get_logger()) detokenize_response = parse_detokenize_response(api_response) @@ -247,12 +210,6 @@ def detokenize(self, request: DetokenizeRequest): except Exception as e: log_error_log(SkyflowMessages.ErrorLogs.DETOKENIZE_REQUEST_REJECTED.value, logger = self.__vault_client.get_logger()) handle_exception(e, self.__vault_client.get_logger()) - except UnauthorizedException as e: - log_error_log(SkyflowMessages.ErrorLogs.DETOKENIZE_REQUEST_REJECTED.value, - logger=self.__vault_client.get_logger()) - handle_exception(e, self.__vault_client.get_logger()) - except ForbiddenException as e: - handle_exception(e, self.__vault_client.get_logger()) def tokenize(self, request: TokenizeRequest): log_info(SkyflowMessages.Info.VALIDATING_TOKENIZE_REQUEST.value, self.__vault_client.get_logger()) @@ -264,23 +221,16 @@ def tokenize(self, request: TokenizeRequest): V1TokenizeRecordRequest(value=item["value"], column_group=item["column_group"]) for item in request.values ] - payload = V1TokenizePayload(tokenization_parameters=records_list) tokens_api = self.__vault_client.get_tokens_api() try: log_info(SkyflowMessages.Info.TOKENIZE_TRIGGERED.value, self.__vault_client.get_logger()) api_response = tokens_api.record_service_tokenize( self.__vault_client.get_vault_id(), - tokenize_payload=payload + tokenization_parameters=records_list ) tokenize_response = parse_tokenize_response(api_response) log_info(SkyflowMessages.Info.TOKENIZE_SUCCESS.value, self.__vault_client.get_logger()) return tokenize_response except Exception as e: log_error_log(SkyflowMessages.ErrorLogs.TOKENIZE_REQUEST_REJECTED.value, logger = self.__vault_client.get_logger()) - handle_exception(e, self.__vault_client.get_logger()) - except UnauthorizedException as e: - log_error_log(SkyflowMessages.ErrorLogs.TOKENIZE_REQUEST_REJECTED.value, - logger=self.__vault_client.get_logger()) - handle_exception(e, self.__vault_client.get_logger()) - except ForbiddenException as e: handle_exception(e, self.__vault_client.get_logger()) \ No newline at end of file diff --git a/skyflow/vault/tokens/_detokenize_request.py b/skyflow/vault/tokens/_detokenize_request.py index 73a5368e..d6a9ed24 100644 --- a/skyflow/vault/tokens/_detokenize_request.py +++ b/skyflow/vault/tokens/_detokenize_request.py @@ -1,5 +1,3 @@ -from skyflow.utils.enums.redaction_type import RedactionType - class DetokenizeRequest: def __init__(self, data, continue_on_error = False): self.data = data diff --git a/tests/client/test_skyflow.py b/tests/client/test_skyflow.py index 621cdee0..3e3681bb 100644 --- a/tests/client/test_skyflow.py +++ b/tests/client/test_skyflow.py @@ -65,7 +65,7 @@ def test_remove_vault_config_valid(self): self.assertNotIn(VALID_VAULT_CONFIG['vault_id'], self.builder._Builder__vault_configs) - @patch('skyflow.client.skyflow.log_error') + @patch('skyflow.utils.logger.log_error') def test_remove_vault_config_invalid(self, mock_log_error): self.builder.add_vault_config(VALID_VAULT_CONFIG) self.builder.build() @@ -159,7 +159,7 @@ def test_remove_connection_config_valid(self): self.assertNotIn(VALID_CONNECTION_CONFIG.get("connection_id"), self.builder._Builder__connection_configs) - @patch('skyflow.client.skyflow.log_error') + @patch('skyflow.utils.logger.log_error') def test_remove_connection_config_invalid(self, mock_log_error): self.builder.add_connection_config(VALID_CONNECTION_CONFIG) self.builder.build() diff --git a/tests/vault/client/test__client.py b/tests/vault/client/test__client.py index cc2e2d42..565b1e6f 100644 --- a/tests/vault/client/test__client.py +++ b/tests/vault/client/test__client.py @@ -1,6 +1,5 @@ import unittest from unittest.mock import patch, MagicMock -from skyflow.generated.rest import Configuration from skyflow.vault.client.client import VaultClient CONFIG = { @@ -31,10 +30,8 @@ def test_set_logger(self): @patch("skyflow.vault.client.client.get_credentials") @patch("skyflow.vault.client.client.get_vault_url") - @patch("skyflow.vault.client.client.Configuration") @patch("skyflow.vault.client.client.VaultClient.initialize_api_client") - def test_initialize_client_configuration(self, mock_init_api_client, mock_config, mock_get_vault_url, - mock_get_credentials): + def test_initialize_client_configuration(self, mock_init_api_client, mock_get_vault_url, mock_get_credentials): mock_get_credentials.return_value = (CREDENTIALS_WITH_API_KEY) mock_get_vault_url.return_value = "https://test-vault-url.com" @@ -42,32 +39,30 @@ def test_initialize_client_configuration(self, mock_init_api_client, mock_config mock_get_credentials.assert_called_once_with(CONFIG["credentials"], None, logger=None) mock_get_vault_url.assert_called_once_with(CONFIG["cluster_id"], CONFIG["env"], CONFIG["vault_id"], logger=None) - mock_config.assert_called_once_with(host="https://test-vault-url.com", access_token="dummy_api_key") mock_init_api_client.assert_called_once() - @patch("skyflow.vault.client.client.ApiClient") + @patch("skyflow.vault.client.client.Skyflow") def test_initialize_api_client(self, mock_api_client): - config = Configuration() - self.vault_client.initialize_api_client(config) - mock_api_client.assert_called_once_with(config) - - @patch("skyflow.vault.client.client.RecordsApi") - def test_get_records_api(self, mock_records_api): - self.vault_client.initialize_api_client(Configuration()) - self.vault_client.get_records_api() - mock_records_api.assert_called_once() - - @patch("skyflow.vault.client.client.TokensApi") - def test_get_tokens_api(self, mock_tokens_api): - self.vault_client.initialize_api_client(Configuration()) - self.vault_client.get_tokens_api() - mock_tokens_api.assert_called_once() - - @patch("skyflow.vault.client.client.QueryApi") - def test_get_query_api(self, mock_query_api): - self.vault_client.initialize_api_client(Configuration()) - self.vault_client.get_query_api() - mock_query_api.assert_called_once() + self.vault_client.initialize_api_client("https://test-vault-url.com", "dummy_token") + mock_api_client.assert_called_once_with(base_url="https://test-vault-url.com", token="dummy_token") + + def test_get_records_api(self): + self.vault_client._VaultClient__api_client = MagicMock() + self.vault_client._VaultClient__api_client.records = MagicMock() + records_api = self.vault_client.get_records_api() + self.assertIsNotNone(records_api) + + def test_get_tokens_api(self): + self.vault_client._VaultClient__api_client = MagicMock() + self.vault_client._VaultClient__api_client.tokens = MagicMock() + tokens_api = self.vault_client.get_tokens_api() + self.assertIsNotNone(tokens_api) + + def test_get_query_api(self): + self.vault_client._VaultClient__api_client = MagicMock() + self.vault_client._VaultClient__api_client.query = MagicMock() + query_api = self.vault_client.get_query_api() + self.assertIsNotNone(query_api) def test_get_vault_id(self): self.assertEqual(self.vault_client.get_vault_id(), CONFIG["vault_id"]) diff --git a/tests/vault/controller/test__vault.py b/tests/vault/controller/test__vault.py index 6e0805e0..89046e65 100644 --- a/tests/vault/controller/test__vault.py +++ b/tests/vault/controller/test__vault.py @@ -1,8 +1,6 @@ import unittest from unittest.mock import Mock, patch -from skyflow.generated.rest import RecordServiceBatchOperationBody, V1BatchRecord, RecordServiceInsertRecordBody, \ - V1FieldRecords, RecordServiceUpdateRecordBody, RecordServiceBulkDeleteRecordBody, QueryServiceExecuteQueryBody, \ - V1DetokenizeRecordRequest, V1DetokenizePayload, V1TokenizePayload, V1TokenizeRecordRequest, RedactionEnumREDACTION +from skyflow.generated.rest import V1BatchRecord, V1FieldRecords, V1DetokenizeRecordRequest, V1TokenizeRecordRequest from skyflow.utils.enums import RedactionType, TokenMode from skyflow.vault.controller import Vault from skyflow.vault.data import InsertRequest, InsertResponse, UpdateResponse, UpdateRequest, DeleteResponse, \ @@ -38,19 +36,15 @@ def test_insert_with_continue_on_error(self, mock_parse_response, mock_validate) continue_on_error=True ) - expected_body = RecordServiceBatchOperationBody( - records=[ - V1BatchRecord( - fields={"field": "value"}, - table_name=TABLE_NAME, - method="POST", - tokenization=True, - upsert="column_name" - ) - ], - continue_on_error=True, - byot="DISABLE" - ) + expected_body = [ + V1BatchRecord( + fields={"field": "value"}, + table_name=TABLE_NAME, + method="POST", + tokenization=True, + upsert="column_name" + ) + ] # Mock API response to contain a mix of successful and failed insertions mock_api_response = Mock() @@ -78,7 +72,12 @@ def test_insert_with_continue_on_error(self, mock_parse_response, mock_validate) # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_batch_operation.assert_called_once_with(VAULT_ID, expected_body) + records_api.record_service_batch_operation.assert_called_once_with( + VAULT_ID, + records=expected_body, + continue_on_error=True, + byot="DISABLE" + ) mock_parse_response.assert_called_once_with(mock_api_response, True) # Assert that the result matches the expected InsertResponse @@ -102,14 +101,9 @@ def test_insert_with_continue_on_error_false(self, mock_parse_response, mock_val ) # Expected API request body based on InsertRequest parameters - expected_body = RecordServiceInsertRecordBody( - records=[ - V1FieldRecords(fields={"field": "value"}) - ], - tokenization=True, - upsert=None, - homogeneous=True - ) + expected_body = [ + V1FieldRecords(fields={"field": "value"}) + ] # Mock API response for a successful insert mock_api_response = Mock() @@ -129,14 +123,34 @@ def test_insert_with_continue_on_error_false(self, mock_parse_response, mock_val # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_insert_record.assert_called_once_with(VAULT_ID, TABLE_NAME, - expected_body) + records_api.record_service_insert_record.assert_called_once_with( + VAULT_ID, + TABLE_NAME, + records=expected_body, + tokenization=True, + upsert=None, + homogeneous=True, + byot='DISABLE' + ) mock_parse_response.assert_called_once_with(mock_api_response, False) # Assert that the result matches the expected InsertResponse self.assertEqual(result.inserted_fields, expected_inserted_fields) self.assertEqual(result.errors, []) # No errors expected + @patch("skyflow.vault.controller._vault.validate_insert_request") + def test_insert_handles_generic_error(self, mock_validate): + request = InsertRequest(table_name="test_table", values=[{"column_name": "value"}], return_tokens=False, + upsert=False, + homogeneous=False, continue_on_error=False, token_mode=Mock()) + records_api = self.vault_client.get_records_api.return_value + records_api.record_service_insert_record.side_effect = Exception("Generic Exception") + + with self.assertRaises(Exception): + self.vault.insert(request) + + records_api.record_service_insert_record.assert_called_once() + @patch("skyflow.vault.controller._vault.validate_insert_request") @patch("skyflow.vault.controller._vault.parse_insert_response") def test_insert_with_continue_on_error_false_when_tokens_are_not_none(self, mock_parse_response, mock_validate): @@ -154,14 +168,9 @@ def test_insert_with_continue_on_error_false_when_tokens_are_not_none(self, mock ) # Expected API request body based on InsertRequest parameters - expected_body = RecordServiceInsertRecordBody( - records=[ - V1FieldRecords(fields={"field": "value"}, tokens={"token_field": "token_val1"}) - ], - tokenization=True, - upsert=None, - homogeneous=True - ) + expected_body = [ + V1FieldRecords(fields={"field": "value"}, tokens={"token_field": "token_val1"}) + ] # Mock API response for a successful insert mock_api_response = Mock() @@ -181,8 +190,15 @@ def test_insert_with_continue_on_error_false_when_tokens_are_not_none(self, mock # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_insert_record.assert_called_once_with(VAULT_ID, TABLE_NAME, - expected_body) + records_api.record_service_insert_record.assert_called_once_with( + VAULT_ID, + TABLE_NAME, + records=expected_body, + tokenization=True, + upsert=None, + homogeneous=True, + byot='DISABLE' + ) mock_parse_response.assert_called_once_with(mock_api_response, False) # Assert that the result matches the expected InsertResponse @@ -204,14 +220,7 @@ def test_update_successful(self, mock_parse_response, mock_validate): ) # Expected payload - expected_payload = RecordServiceUpdateRecordBody( - record=V1FieldRecords( - fields={"field": "new_value"}, - tokens=request.tokens - ), - tokenization=request.return_tokens, - byot=request.token_mode.value - ) + expected_record = V1FieldRecords(fields={"field": "new_value"}, tokens=None) # Mock API response mock_api_response = Mock() @@ -234,9 +243,11 @@ def test_update_successful(self, mock_parse_response, mock_validate): mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) records_api.record_service_update_record.assert_called_once_with( VAULT_ID, - request.table, - request.data["skyflow_id"], - expected_payload + TABLE_NAME, + id="12345", + record=expected_record, + tokenization=True, + byot="DISABLE" ) mock_parse_response.assert_called_once_with(mock_api_response) @@ -244,6 +255,18 @@ def test_update_successful(self, mock_parse_response, mock_validate): self.assertEqual(result.updated_field, expected_updated_field) self.assertEqual(result.errors, []) # No errors expected + @patch("skyflow.vault.controller._vault.validate_update_request") + def test_update_handles_generic_error(self, mock_validate): + request = UpdateRequest(table="test_table", data={"skyflow_id": "123", "field": "value"}, + return_tokens=False) + records_api = self.vault_client.get_records_api.return_value + records_api.record_service_update_record.side_effect = Exception("Generic Exception") + + with self.assertRaises(Exception): + self.vault.update(request) + + records_api.record_service_update_record.assert_called_once() + @patch("skyflow.vault.controller._vault.validate_delete_request") @patch("skyflow.vault.controller._vault.parse_delete_response") def test_delete_successful(self, mock_parse_response, mock_validate): @@ -256,7 +279,7 @@ def test_delete_successful(self, mock_parse_response, mock_validate): ) # Expected payload - expected_payload = RecordServiceBulkDeleteRecordBody(skyflow_ids=request.ids) + expected_payload = ["12345", "67890"] # Mock API response mock_api_response = Mock() @@ -278,8 +301,8 @@ def test_delete_successful(self, mock_parse_response, mock_validate): mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) records_api.record_service_bulk_delete_record.assert_called_once_with( VAULT_ID, - request.table, - expected_payload + TABLE_NAME, + skyflow_ids=["12345", "67890"] ) mock_parse_response.assert_called_once_with(mock_api_response) @@ -287,6 +310,17 @@ def test_delete_successful(self, mock_parse_response, mock_validate): self.assertEqual(result.deleted_ids, expected_deleted_ids) self.assertEqual(result.errors, []) # No errors expected + @patch("skyflow.vault.controller._vault.validate_delete_request") + def test_delete_handles_generic_exception(self, mock_validate): + request = DeleteRequest(table="test_table", ids=["id1", "id2"]) + records_api = self.vault_client.get_records_api.return_value + records_api.record_service_bulk_delete_record.side_effect = Exception("Generic Error") + + with self.assertRaises(Exception): + self.vault.delete(request) + + records_api.record_service_bulk_delete_record.assert_called_once() + @patch("skyflow.vault.controller._vault.validate_get_request") @patch("skyflow.vault.controller._vault.parse_get_response") def test_get_successful(self, mock_parse_response, mock_validate): @@ -405,6 +439,17 @@ def test_get_successful_with_column_values(self, mock_parse_response, mock_valid self.assertEqual(result.data, expected_data) self.assertEqual(result.errors, []) # No errors expected + @patch("skyflow.vault.controller._vault.validate_get_request") + def test_get_handles_generic_error(self, mock_validate): + request = GetRequest(table="test_table", ids=["id1", "id2"]) + records_api = self.vault_client.get_records_api.return_value + records_api.record_service_bulk_get_record.side_effect = Exception("Generic Exception") + + with self.assertRaises(Exception): + self.vault.get(request) + + records_api.record_service_bulk_get_record.assert_called_once() + @patch("skyflow.vault.controller._vault.validate_query_request") @patch("skyflow.vault.controller._vault.parse_query_response") def test_query_successful(self, mock_parse_response, mock_validate): @@ -413,9 +458,6 @@ def test_query_successful(self, mock_parse_response, mock_validate): # Mock request request = QueryRequest(query="SELECT * FROM test_table") - # Expected payload as a QueryServiceExecuteQueryBody instance - expected_payload = QueryServiceExecuteQueryBody(query=request.query) - # Mock API response mock_api_response = Mock() mock_api_response.records = [ @@ -443,7 +485,7 @@ def test_query_successful(self, mock_parse_response, mock_validate): mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) query_api.query_service_execute_query.assert_called_once_with( VAULT_ID, - expected_payload + query="SELECT * FROM test_table" ) mock_parse_response.assert_called_once_with(mock_api_response) @@ -451,6 +493,17 @@ def test_query_successful(self, mock_parse_response, mock_validate): self.assertEqual(result.fields, expected_fields) self.assertEqual(result.errors, []) # No errors expected + @patch("skyflow.vault.controller._vault.validate_query_request") + def test_query_handles_generic_error(self, mock_validate): + request = QueryRequest(query="SELECT * from table_name") + query_api = self.vault_client.get_query_api.return_value + query_api.query_service_execute_query.side_effect = Exception("Generic Exception") + + with self.assertRaises(Exception): + self.vault.query(request) + + query_api.query_service_execute_query.assert_called_once() + @patch("skyflow.vault.controller._vault.validate_detokenize_request") @patch("skyflow.vault.controller._vault.parse_detokenize_response") def test_detokenize_successful(self, mock_parse_response, mock_validate): @@ -458,25 +511,20 @@ def test_detokenize_successful(self, mock_parse_response, mock_validate): data=[ { 'token': 'token1', - 'redaction': RedactionType.PLAIN_TEXT + 'redaction': 'PLAIN_TEXT' }, { 'token': 'token2', - 'redaction': RedactionType.PLAIN_TEXT + 'redaction': 'PLAIN_TEXT' } ], continue_on_error=False ) - # Expected payload as a V1DetokenizePayload instance - tokens_list = [ - V1DetokenizeRecordRequest(token="token1", redaction=RedactionEnumREDACTION.PLAIN_TEXT), - V1DetokenizeRecordRequest(token="token2", redaction=RedactionEnumREDACTION.PLAIN_TEXT) + expected_tokens_list = [ + V1DetokenizeRecordRequest(token="token1", redaction="PLAIN_TEXT"), + V1DetokenizeRecordRequest(token="token2", redaction="PLAIN_TEXT") ] - expected_payload = V1DetokenizePayload( - detokenization_parameters=tokens_list, - continue_on_error=request.continue_on_error - ) # Mock API response mock_api_response = Mock() @@ -504,7 +552,8 @@ def test_detokenize_successful(self, mock_parse_response, mock_validate): mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) tokens_api.record_service_detokenize.assert_called_once_with( VAULT_ID, - detokenize_payload=expected_payload + detokenization_parameters=expected_tokens_list, + continue_on_error=False ) mock_parse_response.assert_called_once_with(mock_api_response) @@ -512,6 +561,29 @@ def test_detokenize_successful(self, mock_parse_response, mock_validate): self.assertEqual(result.detokenized_fields, expected_fields) self.assertEqual(result.errors, []) # No errors expected + @patch("skyflow.vault.controller._vault.validate_detokenize_request") + def test_detokenize_handles_generic_error(self, mock_validate): + request = DetokenizeRequest( + data=[ + { + 'token': 'token1', + 'redaction': RedactionType.PLAIN_TEXT + }, + { + 'token': 'token2', + 'redaction': RedactionType.PLAIN_TEXT + } + ], + continue_on_error=False + ) + tokens_api = self.vault_client.get_tokens_api.return_value + tokens_api.record_service_detokenize.side_effect = Exception("Generic Error") + + with self.assertRaises(Exception): + self.vault.detokenize(request) + + tokens_api.record_service_detokenize.assert_called_once() + @patch("skyflow.vault.controller._vault.validate_tokenize_request") @patch("skyflow.vault.controller._vault.parse_tokenize_response") def test_tokenize_successful(self, mock_parse_response, mock_validate): @@ -525,12 +597,10 @@ def test_tokenize_successful(self, mock_parse_response, mock_validate): ] ) - # Expected payload as a V1TokenizePayload instance - records_list = [ + expected_records_list = [ V1TokenizeRecordRequest(value="value1", column_group="group1"), V1TokenizeRecordRequest(value="value2", column_group="group2") ] - expected_payload = V1TokenizePayload(tokenization_parameters=records_list) # Mock API response mock_api_response = Mock() @@ -558,9 +628,25 @@ def test_tokenize_successful(self, mock_parse_response, mock_validate): mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) tokens_api.record_service_tokenize.assert_called_once_with( VAULT_ID, - tokenize_payload=expected_payload + tokenization_parameters=expected_records_list ) mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected TokenizeResponse - self.assertEqual(result.tokenized_fields, expected_fields) \ No newline at end of file + self.assertEqual(result.tokenized_fields, expected_fields) + + @patch("skyflow.vault.controller._vault.validate_tokenize_request") + def test_tokenize_handles_generic_error(self, mock_validate): + request = TokenizeRequest( + values=[ + {"value": "value1", "column_group": "group1"}, + {"value": "value2", "column_group": "group2"} + ] + ) + tokens_api = self.vault_client.get_tokens_api.return_value + tokens_api.record_service_tokenize.side_effect = Exception("Generic Error") + + with self.assertRaises(Exception): + self.vault.tokenize(request) + + tokens_api.record_service_tokenize.assert_called_once() From 343b88c47f12a8ad0623a2901e1c8f55566cba00 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Mon, 17 Mar 2025 13:21:19 +0000 Subject: [PATCH 10/24] [AUTOMATED] Private Release 2.0.0b2.dev0+f760bc0 --- setup.py | 2 +- skyflow/utils/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 10181764..fc1f9e6a 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ if sys.version_info < (3, 8): raise RuntimeError("skyflow requires Python 3.8+") -current_version = '2.0.0b1.dev0+3d4ee51' +current_version = '2.0.0b2.dev0+f760bc0' setup( name='skyflow', diff --git a/skyflow/utils/_version.py b/skyflow/utils/_version.py index 522115a4..d73d9196 100644 --- a/skyflow/utils/_version.py +++ b/skyflow/utils/_version.py @@ -1 +1 @@ -SDK_VERSION = '2.0.0b1.dev0+3d4ee51' \ No newline at end of file +SDK_VERSION = '2.0.0b2.dev0+f760bc0' \ No newline at end of file From 3f3a2971d38246ce4f7696fa21517a02bb003d5a Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 2 May 2025 19:24:21 +0530 Subject: [PATCH 11/24] SK-1909 Update generated code --- skyflow/generated/rest/__init__.py | 2 + skyflow/generated/rest/audit/__init__.py | 2 + skyflow/generated/rest/audit/client.py | 266 ++- skyflow/generated/rest/audit/raw_client.py | 482 +++++ .../generated/rest/audit/types/__init__.py | 2 + .../generated/rest/authentication/__init__.py | 2 + .../generated/rest/authentication/client.py | 196 +-- .../rest/authentication/raw_client.py | 235 +++ skyflow/generated/rest/bin_lookup/__init__.py | 2 + skyflow/generated/rest/bin_lookup/client.py | 151 +- .../generated/rest/bin_lookup/raw_client.py | 177 ++ skyflow/generated/rest/client.py | 46 +- skyflow/generated/rest/core/__init__.py | 5 + skyflow/generated/rest/core/api_error.py | 18 +- skyflow/generated/rest/core/client_wrapper.py | 8 +- skyflow/generated/rest/core/http_client.py | 2 - skyflow/generated/rest/core/http_response.py | 55 + .../generated/rest/core/jsonable_encoder.py | 1 - .../generated/rest/core/pydantic_utilities.py | 179 +- skyflow/generated/rest/core/serialization.py | 10 +- skyflow/generated/rest/errors/__init__.py | 2 + .../rest/errors/bad_request_error.py | 3 +- .../generated/rest/errors/not_found_error.py | 3 +- .../rest/errors/unauthorized_error.py | 3 +- skyflow/generated/rest/query/__init__.py | 2 + skyflow/generated/rest/query/client.py | 137 +- skyflow/generated/rest/query/raw_client.py | 152 ++ skyflow/generated/rest/records/__init__.py | 2 + skyflow/generated/rest/records/client.py | 1283 +++----------- skyflow/generated/rest/records/raw_client.py | 1545 +++++++++++++++++ .../generated/rest/records/types/__init__.py | 2 + skyflow/generated/rest/tokens/__init__.py | 2 + skyflow/generated/rest/tokens/client.py | 287 +-- skyflow/generated/rest/tokens/raw_client.py | 318 ++++ skyflow/generated/rest/types/__init__.py | 2 + .../rest/types/audit_event_context.py | 10 +- .../generated/rest/types/audit_event_data.py | 4 +- .../rest/types/audit_event_http_info.py | 8 +- .../generated/rest/types/googlerpc_status.py | 6 +- skyflow/generated/rest/types/protobuf_any.py | 8 +- .../rest/types/v_1_audit_after_options.py | 4 +- .../rest/types/v_1_audit_event_response.py | 4 +- .../rest/types/v_1_audit_response.py | 8 +- .../rest/types/v_1_audit_response_event.py | 12 +- .../types/v_1_audit_response_event_request.py | 10 +- .../types/v_1_batch_operation_response.py | 8 +- .../generated/rest/types/v_1_batch_record.py | 4 +- .../rest/types/v_1_bin_list_response.py | 6 +- .../types/v_1_bulk_delete_record_response.py | 8 +- .../types/v_1_bulk_get_record_response.py | 6 +- skyflow/generated/rest/types/v_1_card.py | 8 +- .../rest/types/v_1_delete_file_response.py | 4 +- .../rest/types/v_1_delete_record_response.py | 4 +- .../types/v_1_detokenize_record_request.py | 4 +- .../types/v_1_detokenize_record_response.py | 6 +- .../rest/types/v_1_detokenize_response.py | 6 +- .../generated/rest/types/v_1_field_records.py | 4 +- .../rest/types/v_1_get_auth_token_response.py | 8 +- .../v_1_get_file_scan_status_response.py | 6 +- .../rest/types/v_1_get_query_response.py | 6 +- .../rest/types/v_1_insert_record_response.py | 6 +- .../rest/types/v_1_record_meta_properties.py | 4 +- .../rest/types/v_1_tokenize_record_request.py | 4 +- .../types/v_1_tokenize_record_response.py | 4 +- .../rest/types/v_1_tokenize_response.py | 6 +- .../rest/types/v_1_update_record_response.py | 4 +- .../rest/types/v_1_vault_field_mapping.py | 4 +- .../rest/types/v_1_vault_schema_config.py | 4 +- skyflow/generated/rest/version.py | 2 +- 69 files changed, 3749 insertions(+), 2035 deletions(-) create mode 100644 skyflow/generated/rest/audit/raw_client.py create mode 100644 skyflow/generated/rest/authentication/raw_client.py create mode 100644 skyflow/generated/rest/bin_lookup/raw_client.py create mode 100644 skyflow/generated/rest/core/http_response.py create mode 100644 skyflow/generated/rest/query/raw_client.py create mode 100644 skyflow/generated/rest/records/raw_client.py create mode 100644 skyflow/generated/rest/tokens/raw_client.py diff --git a/skyflow/generated/rest/__init__.py b/skyflow/generated/rest/__init__.py index 5cacae7e..af42a8fa 100644 --- a/skyflow/generated/rest/__init__.py +++ b/skyflow/generated/rest/__init__.py @@ -1,5 +1,7 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .types import ( AuditEventAuditResourceType, AuditEventContext, diff --git a/skyflow/generated/rest/audit/__init__.py b/skyflow/generated/rest/audit/__init__.py index 38fe28d3..e3b20ff0 100644 --- a/skyflow/generated/rest/audit/__init__.py +++ b/skyflow/generated/rest/audit/__init__.py @@ -1,5 +1,7 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .types import ( AuditServiceListAuditEventsRequestFilterOpsActionType, AuditServiceListAuditEventsRequestFilterOpsContextAccessType, diff --git a/skyflow/generated/rest/audit/client.py b/skyflow/generated/rest/audit/client.py index 3b4d329a..7e22b077 100644 --- a/skyflow/generated/rest/audit/client.py +++ b/skyflow/generated/rest/audit/client.py @@ -1,37 +1,45 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import SyncClientWrapper import typing -from .types.audit_service_list_audit_events_request_filter_ops_context_actor_type import ( - AuditServiceListAuditEventsRequestFilterOpsContextActorType, + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..types.v_1_audit_response import V1AuditResponse +from .raw_client import AsyncRawAuditClient, RawAuditClient +from .types.audit_service_list_audit_events_request_filter_ops_action_type import ( + AuditServiceListAuditEventsRequestFilterOpsActionType, ) from .types.audit_service_list_audit_events_request_filter_ops_context_access_type import ( AuditServiceListAuditEventsRequestFilterOpsContextAccessType, ) +from .types.audit_service_list_audit_events_request_filter_ops_context_actor_type import ( + AuditServiceListAuditEventsRequestFilterOpsContextActorType, +) from .types.audit_service_list_audit_events_request_filter_ops_context_auth_mode import ( AuditServiceListAuditEventsRequestFilterOpsContextAuthMode, ) -from .types.audit_service_list_audit_events_request_filter_ops_action_type import ( - AuditServiceListAuditEventsRequestFilterOpsActionType, -) from .types.audit_service_list_audit_events_request_filter_ops_resource_type import ( AuditServiceListAuditEventsRequestFilterOpsResourceType, ) from .types.audit_service_list_audit_events_request_sort_ops_order_by import ( AuditServiceListAuditEventsRequestSortOpsOrderBy, ) -from ..core.request_options import RequestOptions -from ..types.v_1_audit_response import V1AuditResponse -from ..core.pydantic_utilities import parse_obj_as -from ..errors.not_found_error import NotFoundError -from json.decoder import JSONDecodeError -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper class AuditClient: def __init__(self, *, client_wrapper: SyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = RawAuditClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawAuditClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawAuditClient + """ + return self._raw_client def audit_service_list_audit_events( self, @@ -192,82 +200,62 @@ def audit_service_list_audit_events( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.audit.audit_service_list_audit_events( - filter_ops_account_id="filterOps.accountID", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.audit.audit_service_list_audit_events(filter_ops_account_id='filterOps.accountID', ) """ - _response = self._client_wrapper.httpx_client.request( - "v1/audit/events", - method="GET", - params={ - "filterOps.context.changeID": filter_ops_context_change_id, - "filterOps.context.requestID": filter_ops_context_request_id, - "filterOps.context.traceID": filter_ops_context_trace_id, - "filterOps.context.sessionID": filter_ops_context_session_id, - "filterOps.context.actor": filter_ops_context_actor, - "filterOps.context.actorType": filter_ops_context_actor_type, - "filterOps.context.accessType": filter_ops_context_access_type, - "filterOps.context.ipAddress": filter_ops_context_ip_address, - "filterOps.context.origin": filter_ops_context_origin, - "filterOps.context.authMode": filter_ops_context_auth_mode, - "filterOps.context.jwtID": filter_ops_context_jwt_id, - "filterOps.context.bearerTokenContextID": filter_ops_context_bearer_token_context_id, - "filterOps.parentAccountID": filter_ops_parent_account_id, - "filterOps.accountID": filter_ops_account_id, - "filterOps.workspaceID": filter_ops_workspace_id, - "filterOps.vaultID": filter_ops_vault_id, - "filterOps.resourceIDs": filter_ops_resource_i_ds, - "filterOps.actionType": filter_ops_action_type, - "filterOps.resourceType": filter_ops_resource_type, - "filterOps.tags": filter_ops_tags, - "filterOps.responseCode": filter_ops_response_code, - "filterOps.startTime": filter_ops_start_time, - "filterOps.endTime": filter_ops_end_time, - "filterOps.apiName": filter_ops_api_name, - "filterOps.responseMessage": filter_ops_response_message, - "filterOps.httpMethod": filter_ops_http_method, - "filterOps.httpURI": filter_ops_http_uri, - "sortOps.sortBy": sort_ops_sort_by, - "sortOps.orderBy": sort_ops_order_by, - "afterOps.timestamp": after_ops_timestamp, - "afterOps.changeID": after_ops_change_id, - "limit": limit, - "offset": offset, - }, + _response = self._raw_client.audit_service_list_audit_events( + filter_ops_account_id=filter_ops_account_id, + filter_ops_context_change_id=filter_ops_context_change_id, + filter_ops_context_request_id=filter_ops_context_request_id, + filter_ops_context_trace_id=filter_ops_context_trace_id, + filter_ops_context_session_id=filter_ops_context_session_id, + filter_ops_context_actor=filter_ops_context_actor, + filter_ops_context_actor_type=filter_ops_context_actor_type, + filter_ops_context_access_type=filter_ops_context_access_type, + filter_ops_context_ip_address=filter_ops_context_ip_address, + filter_ops_context_origin=filter_ops_context_origin, + filter_ops_context_auth_mode=filter_ops_context_auth_mode, + filter_ops_context_jwt_id=filter_ops_context_jwt_id, + filter_ops_context_bearer_token_context_id=filter_ops_context_bearer_token_context_id, + filter_ops_parent_account_id=filter_ops_parent_account_id, + filter_ops_workspace_id=filter_ops_workspace_id, + filter_ops_vault_id=filter_ops_vault_id, + filter_ops_resource_i_ds=filter_ops_resource_i_ds, + filter_ops_action_type=filter_ops_action_type, + filter_ops_resource_type=filter_ops_resource_type, + filter_ops_tags=filter_ops_tags, + filter_ops_response_code=filter_ops_response_code, + filter_ops_start_time=filter_ops_start_time, + filter_ops_end_time=filter_ops_end_time, + filter_ops_api_name=filter_ops_api_name, + filter_ops_response_message=filter_ops_response_message, + filter_ops_http_method=filter_ops_http_method, + filter_ops_http_uri=filter_ops_http_uri, + sort_ops_sort_by=sort_ops_sort_by, + sort_ops_order_by=sort_ops_order_by, + after_ops_timestamp=after_ops_timestamp, + after_ops_change_id=after_ops_change_id, + limit=limit, + offset=offset, request_options=request_options, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1AuditResponse, - parse_obj_as( - type_=V1AuditResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data class AsyncAuditClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = AsyncRawAuditClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawAuditClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawAuditClient + """ + return self._raw_client async def audit_service_list_audit_events( self, @@ -427,83 +415,47 @@ async def audit_service_list_audit_events( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.audit.audit_service_list_audit_events( - filter_ops_account_id="filterOps.accountID", - ) - - + await client.audit.audit_service_list_audit_events(filter_ops_account_id='filterOps.accountID', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - "v1/audit/events", - method="GET", - params={ - "filterOps.context.changeID": filter_ops_context_change_id, - "filterOps.context.requestID": filter_ops_context_request_id, - "filterOps.context.traceID": filter_ops_context_trace_id, - "filterOps.context.sessionID": filter_ops_context_session_id, - "filterOps.context.actor": filter_ops_context_actor, - "filterOps.context.actorType": filter_ops_context_actor_type, - "filterOps.context.accessType": filter_ops_context_access_type, - "filterOps.context.ipAddress": filter_ops_context_ip_address, - "filterOps.context.origin": filter_ops_context_origin, - "filterOps.context.authMode": filter_ops_context_auth_mode, - "filterOps.context.jwtID": filter_ops_context_jwt_id, - "filterOps.context.bearerTokenContextID": filter_ops_context_bearer_token_context_id, - "filterOps.parentAccountID": filter_ops_parent_account_id, - "filterOps.accountID": filter_ops_account_id, - "filterOps.workspaceID": filter_ops_workspace_id, - "filterOps.vaultID": filter_ops_vault_id, - "filterOps.resourceIDs": filter_ops_resource_i_ds, - "filterOps.actionType": filter_ops_action_type, - "filterOps.resourceType": filter_ops_resource_type, - "filterOps.tags": filter_ops_tags, - "filterOps.responseCode": filter_ops_response_code, - "filterOps.startTime": filter_ops_start_time, - "filterOps.endTime": filter_ops_end_time, - "filterOps.apiName": filter_ops_api_name, - "filterOps.responseMessage": filter_ops_response_message, - "filterOps.httpMethod": filter_ops_http_method, - "filterOps.httpURI": filter_ops_http_uri, - "sortOps.sortBy": sort_ops_sort_by, - "sortOps.orderBy": sort_ops_order_by, - "afterOps.timestamp": after_ops_timestamp, - "afterOps.changeID": after_ops_change_id, - "limit": limit, - "offset": offset, - }, + _response = await self._raw_client.audit_service_list_audit_events( + filter_ops_account_id=filter_ops_account_id, + filter_ops_context_change_id=filter_ops_context_change_id, + filter_ops_context_request_id=filter_ops_context_request_id, + filter_ops_context_trace_id=filter_ops_context_trace_id, + filter_ops_context_session_id=filter_ops_context_session_id, + filter_ops_context_actor=filter_ops_context_actor, + filter_ops_context_actor_type=filter_ops_context_actor_type, + filter_ops_context_access_type=filter_ops_context_access_type, + filter_ops_context_ip_address=filter_ops_context_ip_address, + filter_ops_context_origin=filter_ops_context_origin, + filter_ops_context_auth_mode=filter_ops_context_auth_mode, + filter_ops_context_jwt_id=filter_ops_context_jwt_id, + filter_ops_context_bearer_token_context_id=filter_ops_context_bearer_token_context_id, + filter_ops_parent_account_id=filter_ops_parent_account_id, + filter_ops_workspace_id=filter_ops_workspace_id, + filter_ops_vault_id=filter_ops_vault_id, + filter_ops_resource_i_ds=filter_ops_resource_i_ds, + filter_ops_action_type=filter_ops_action_type, + filter_ops_resource_type=filter_ops_resource_type, + filter_ops_tags=filter_ops_tags, + filter_ops_response_code=filter_ops_response_code, + filter_ops_start_time=filter_ops_start_time, + filter_ops_end_time=filter_ops_end_time, + filter_ops_api_name=filter_ops_api_name, + filter_ops_response_message=filter_ops_response_message, + filter_ops_http_method=filter_ops_http_method, + filter_ops_http_uri=filter_ops_http_uri, + sort_ops_sort_by=sort_ops_sort_by, + sort_ops_order_by=sort_ops_order_by, + after_ops_timestamp=after_ops_timestamp, + after_ops_change_id=after_ops_change_id, + limit=limit, + offset=offset, request_options=request_options, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1AuditResponse, - parse_obj_as( - type_=V1AuditResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data diff --git a/skyflow/generated/rest/audit/raw_client.py b/skyflow/generated/rest/audit/raw_client.py new file mode 100644 index 00000000..9762e46d --- /dev/null +++ b/skyflow/generated/rest/audit/raw_client.py @@ -0,0 +1,482 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..errors.not_found_error import NotFoundError +from ..types.v_1_audit_response import V1AuditResponse +from .types.audit_service_list_audit_events_request_filter_ops_action_type import ( + AuditServiceListAuditEventsRequestFilterOpsActionType, +) +from .types.audit_service_list_audit_events_request_filter_ops_context_access_type import ( + AuditServiceListAuditEventsRequestFilterOpsContextAccessType, +) +from .types.audit_service_list_audit_events_request_filter_ops_context_actor_type import ( + AuditServiceListAuditEventsRequestFilterOpsContextActorType, +) +from .types.audit_service_list_audit_events_request_filter_ops_context_auth_mode import ( + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode, +) +from .types.audit_service_list_audit_events_request_filter_ops_resource_type import ( + AuditServiceListAuditEventsRequestFilterOpsResourceType, +) +from .types.audit_service_list_audit_events_request_sort_ops_order_by import ( + AuditServiceListAuditEventsRequestSortOpsOrderBy, +) + + +class RawAuditClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def audit_service_list_audit_events( + self, + *, + filter_ops_account_id: str, + filter_ops_context_change_id: typing.Optional[str] = None, + filter_ops_context_request_id: typing.Optional[str] = None, + filter_ops_context_trace_id: typing.Optional[str] = None, + filter_ops_context_session_id: typing.Optional[str] = None, + filter_ops_context_actor: typing.Optional[str] = None, + filter_ops_context_actor_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextActorType + ] = None, + filter_ops_context_access_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAccessType + ] = None, + filter_ops_context_ip_address: typing.Optional[str] = None, + filter_ops_context_origin: typing.Optional[str] = None, + filter_ops_context_auth_mode: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode + ] = None, + filter_ops_context_jwt_id: typing.Optional[str] = None, + filter_ops_context_bearer_token_context_id: typing.Optional[str] = None, + filter_ops_parent_account_id: typing.Optional[str] = None, + filter_ops_workspace_id: typing.Optional[str] = None, + filter_ops_vault_id: typing.Optional[str] = None, + filter_ops_resource_i_ds: typing.Optional[str] = None, + filter_ops_action_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] = None, + filter_ops_resource_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] = None, + filter_ops_tags: typing.Optional[str] = None, + filter_ops_response_code: typing.Optional[int] = None, + filter_ops_start_time: typing.Optional[str] = None, + filter_ops_end_time: typing.Optional[str] = None, + filter_ops_api_name: typing.Optional[str] = None, + filter_ops_response_message: typing.Optional[str] = None, + filter_ops_http_method: typing.Optional[str] = None, + filter_ops_http_uri: typing.Optional[str] = None, + sort_ops_sort_by: typing.Optional[str] = None, + sort_ops_order_by: typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] = None, + after_ops_timestamp: typing.Optional[str] = None, + after_ops_change_id: typing.Optional[str] = None, + limit: typing.Optional[int] = None, + offset: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1AuditResponse]: + """ + Lists audit events that match query parameters. + + Parameters + ---------- + filter_ops_account_id : str + Resources with the specified account ID. + + filter_ops_context_change_id : typing.Optional[str] + ID for the audit event. + + filter_ops_context_request_id : typing.Optional[str] + ID for the request that caused the event. + + filter_ops_context_trace_id : typing.Optional[str] + ID for the request set by the service that received the request. + + filter_ops_context_session_id : typing.Optional[str] + ID for the session in which the request was sent. + + filter_ops_context_actor : typing.Optional[str] + Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. + + filter_ops_context_actor_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextActorType] + Type of member who sent the request. + + filter_ops_context_access_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAccessType] + Type of access for the request. + + filter_ops_context_ip_address : typing.Optional[str] + IP Address of the client that made the request. + + filter_ops_context_origin : typing.Optional[str] + HTTP Origin request header (including scheme, hostname, and port) of the request. + + filter_ops_context_auth_mode : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAuthMode] + Authentication mode the `actor` used. + + filter_ops_context_jwt_id : typing.Optional[str] + ID of the JWT token. + + filter_ops_context_bearer_token_context_id : typing.Optional[str] + Embedded User Context. + + filter_ops_parent_account_id : typing.Optional[str] + Resources with the specified parent account ID. + + filter_ops_workspace_id : typing.Optional[str] + Resources with the specified workspace ID. + + filter_ops_vault_id : typing.Optional[str] + Resources with the specified vault ID. + + filter_ops_resource_i_ds : typing.Optional[str] + Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "\/\". For example, "VAULT/12345, USER/67890". + + filter_ops_action_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] + Events with the specified action type. + + filter_ops_resource_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] + Resources with the specified type. + + filter_ops_tags : typing.Optional[str] + Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get". + + filter_ops_response_code : typing.Optional[int] + HTTP response code of the request. + + filter_ops_start_time : typing.Optional[str] + Start timestamp for the query, in SQL format. + + filter_ops_end_time : typing.Optional[str] + End timestamp for the query, in SQL format. + + filter_ops_api_name : typing.Optional[str] + Name of the API called in the request. + + filter_ops_response_message : typing.Optional[str] + Response message of the request. + + filter_ops_http_method : typing.Optional[str] + HTTP method of the request. + + filter_ops_http_uri : typing.Optional[str] + HTTP URI of the request. + + sort_ops_sort_by : typing.Optional[str] + Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase"). + + sort_ops_order_by : typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] + Ascending or descending ordering of results. + + after_ops_timestamp : typing.Optional[str] + Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + after_ops_change_id : typing.Optional[str] + Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + limit : typing.Optional[int] + Number of results to return. + + offset : typing.Optional[int] + Record position at which to start returning results. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1AuditResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + "v1/audit/events", + method="GET", + params={ + "filterOps.context.changeID": filter_ops_context_change_id, + "filterOps.context.requestID": filter_ops_context_request_id, + "filterOps.context.traceID": filter_ops_context_trace_id, + "filterOps.context.sessionID": filter_ops_context_session_id, + "filterOps.context.actor": filter_ops_context_actor, + "filterOps.context.actorType": filter_ops_context_actor_type, + "filterOps.context.accessType": filter_ops_context_access_type, + "filterOps.context.ipAddress": filter_ops_context_ip_address, + "filterOps.context.origin": filter_ops_context_origin, + "filterOps.context.authMode": filter_ops_context_auth_mode, + "filterOps.context.jwtID": filter_ops_context_jwt_id, + "filterOps.context.bearerTokenContextID": filter_ops_context_bearer_token_context_id, + "filterOps.parentAccountID": filter_ops_parent_account_id, + "filterOps.accountID": filter_ops_account_id, + "filterOps.workspaceID": filter_ops_workspace_id, + "filterOps.vaultID": filter_ops_vault_id, + "filterOps.resourceIDs": filter_ops_resource_i_ds, + "filterOps.actionType": filter_ops_action_type, + "filterOps.resourceType": filter_ops_resource_type, + "filterOps.tags": filter_ops_tags, + "filterOps.responseCode": filter_ops_response_code, + "filterOps.startTime": filter_ops_start_time, + "filterOps.endTime": filter_ops_end_time, + "filterOps.apiName": filter_ops_api_name, + "filterOps.responseMessage": filter_ops_response_message, + "filterOps.httpMethod": filter_ops_http_method, + "filterOps.httpURI": filter_ops_http_uri, + "sortOps.sortBy": sort_ops_sort_by, + "sortOps.orderBy": sort_ops_order_by, + "afterOps.timestamp": after_ops_timestamp, + "afterOps.changeID": after_ops_change_id, + "limit": limit, + "offset": offset, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1AuditResponse, + parse_obj_as( + type_=V1AuditResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + +class AsyncRawAuditClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def audit_service_list_audit_events( + self, + *, + filter_ops_account_id: str, + filter_ops_context_change_id: typing.Optional[str] = None, + filter_ops_context_request_id: typing.Optional[str] = None, + filter_ops_context_trace_id: typing.Optional[str] = None, + filter_ops_context_session_id: typing.Optional[str] = None, + filter_ops_context_actor: typing.Optional[str] = None, + filter_ops_context_actor_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextActorType + ] = None, + filter_ops_context_access_type: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAccessType + ] = None, + filter_ops_context_ip_address: typing.Optional[str] = None, + filter_ops_context_origin: typing.Optional[str] = None, + filter_ops_context_auth_mode: typing.Optional[ + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode + ] = None, + filter_ops_context_jwt_id: typing.Optional[str] = None, + filter_ops_context_bearer_token_context_id: typing.Optional[str] = None, + filter_ops_parent_account_id: typing.Optional[str] = None, + filter_ops_workspace_id: typing.Optional[str] = None, + filter_ops_vault_id: typing.Optional[str] = None, + filter_ops_resource_i_ds: typing.Optional[str] = None, + filter_ops_action_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] = None, + filter_ops_resource_type: typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] = None, + filter_ops_tags: typing.Optional[str] = None, + filter_ops_response_code: typing.Optional[int] = None, + filter_ops_start_time: typing.Optional[str] = None, + filter_ops_end_time: typing.Optional[str] = None, + filter_ops_api_name: typing.Optional[str] = None, + filter_ops_response_message: typing.Optional[str] = None, + filter_ops_http_method: typing.Optional[str] = None, + filter_ops_http_uri: typing.Optional[str] = None, + sort_ops_sort_by: typing.Optional[str] = None, + sort_ops_order_by: typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] = None, + after_ops_timestamp: typing.Optional[str] = None, + after_ops_change_id: typing.Optional[str] = None, + limit: typing.Optional[int] = None, + offset: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1AuditResponse]: + """ + Lists audit events that match query parameters. + + Parameters + ---------- + filter_ops_account_id : str + Resources with the specified account ID. + + filter_ops_context_change_id : typing.Optional[str] + ID for the audit event. + + filter_ops_context_request_id : typing.Optional[str] + ID for the request that caused the event. + + filter_ops_context_trace_id : typing.Optional[str] + ID for the request set by the service that received the request. + + filter_ops_context_session_id : typing.Optional[str] + ID for the session in which the request was sent. + + filter_ops_context_actor : typing.Optional[str] + Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. + + filter_ops_context_actor_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextActorType] + Type of member who sent the request. + + filter_ops_context_access_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAccessType] + Type of access for the request. + + filter_ops_context_ip_address : typing.Optional[str] + IP Address of the client that made the request. + + filter_ops_context_origin : typing.Optional[str] + HTTP Origin request header (including scheme, hostname, and port) of the request. + + filter_ops_context_auth_mode : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsContextAuthMode] + Authentication mode the `actor` used. + + filter_ops_context_jwt_id : typing.Optional[str] + ID of the JWT token. + + filter_ops_context_bearer_token_context_id : typing.Optional[str] + Embedded User Context. + + filter_ops_parent_account_id : typing.Optional[str] + Resources with the specified parent account ID. + + filter_ops_workspace_id : typing.Optional[str] + Resources with the specified workspace ID. + + filter_ops_vault_id : typing.Optional[str] + Resources with the specified vault ID. + + filter_ops_resource_i_ds : typing.Optional[str] + Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "\/\". For example, "VAULT/12345, USER/67890". + + filter_ops_action_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsActionType] + Events with the specified action type. + + filter_ops_resource_type : typing.Optional[AuditServiceListAuditEventsRequestFilterOpsResourceType] + Resources with the specified type. + + filter_ops_tags : typing.Optional[str] + Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get". + + filter_ops_response_code : typing.Optional[int] + HTTP response code of the request. + + filter_ops_start_time : typing.Optional[str] + Start timestamp for the query, in SQL format. + + filter_ops_end_time : typing.Optional[str] + End timestamp for the query, in SQL format. + + filter_ops_api_name : typing.Optional[str] + Name of the API called in the request. + + filter_ops_response_message : typing.Optional[str] + Response message of the request. + + filter_ops_http_method : typing.Optional[str] + HTTP method of the request. + + filter_ops_http_uri : typing.Optional[str] + HTTP URI of the request. + + sort_ops_sort_by : typing.Optional[str] + Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase"). + + sort_ops_order_by : typing.Optional[AuditServiceListAuditEventsRequestSortOpsOrderBy] + Ascending or descending ordering of results. + + after_ops_timestamp : typing.Optional[str] + Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + after_ops_change_id : typing.Optional[str] + Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + + limit : typing.Optional[int] + Number of results to return. + + offset : typing.Optional[int] + Record position at which to start returning results. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1AuditResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + "v1/audit/events", + method="GET", + params={ + "filterOps.context.changeID": filter_ops_context_change_id, + "filterOps.context.requestID": filter_ops_context_request_id, + "filterOps.context.traceID": filter_ops_context_trace_id, + "filterOps.context.sessionID": filter_ops_context_session_id, + "filterOps.context.actor": filter_ops_context_actor, + "filterOps.context.actorType": filter_ops_context_actor_type, + "filterOps.context.accessType": filter_ops_context_access_type, + "filterOps.context.ipAddress": filter_ops_context_ip_address, + "filterOps.context.origin": filter_ops_context_origin, + "filterOps.context.authMode": filter_ops_context_auth_mode, + "filterOps.context.jwtID": filter_ops_context_jwt_id, + "filterOps.context.bearerTokenContextID": filter_ops_context_bearer_token_context_id, + "filterOps.parentAccountID": filter_ops_parent_account_id, + "filterOps.accountID": filter_ops_account_id, + "filterOps.workspaceID": filter_ops_workspace_id, + "filterOps.vaultID": filter_ops_vault_id, + "filterOps.resourceIDs": filter_ops_resource_i_ds, + "filterOps.actionType": filter_ops_action_type, + "filterOps.resourceType": filter_ops_resource_type, + "filterOps.tags": filter_ops_tags, + "filterOps.responseCode": filter_ops_response_code, + "filterOps.startTime": filter_ops_start_time, + "filterOps.endTime": filter_ops_end_time, + "filterOps.apiName": filter_ops_api_name, + "filterOps.responseMessage": filter_ops_response_message, + "filterOps.httpMethod": filter_ops_http_method, + "filterOps.httpURI": filter_ops_http_uri, + "sortOps.sortBy": sort_ops_sort_by, + "sortOps.orderBy": sort_ops_order_by, + "afterOps.timestamp": after_ops_timestamp, + "afterOps.changeID": after_ops_change_id, + "limit": limit, + "offset": offset, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1AuditResponse, + parse_obj_as( + type_=V1AuditResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/audit/types/__init__.py b/skyflow/generated/rest/audit/types/__init__.py index 39f38866..71e29b43 100644 --- a/skyflow/generated/rest/audit/types/__init__.py +++ b/skyflow/generated/rest/audit/types/__init__.py @@ -1,5 +1,7 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .audit_service_list_audit_events_request_filter_ops_action_type import ( AuditServiceListAuditEventsRequestFilterOpsActionType, ) diff --git a/skyflow/generated/rest/authentication/__init__.py b/skyflow/generated/rest/authentication/__init__.py index f3ea2659..5cde0202 100644 --- a/skyflow/generated/rest/authentication/__init__.py +++ b/skyflow/generated/rest/authentication/__init__.py @@ -1,2 +1,4 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + diff --git a/skyflow/generated/rest/authentication/client.py b/skyflow/generated/rest/authentication/client.py index c4825e27..81408a26 100644 --- a/skyflow/generated/rest/authentication/client.py +++ b/skyflow/generated/rest/authentication/client.py @@ -1,16 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing -from ..core.client_wrapper import SyncClientWrapper + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.request_options import RequestOptions from ..types.v_1_get_auth_token_response import V1GetAuthTokenResponse -from ..core.pydantic_utilities import parse_obj_as -from ..errors.bad_request_error import BadRequestError -from ..errors.unauthorized_error import UnauthorizedError -from ..errors.not_found_error import NotFoundError -from json.decoder import JSONDecodeError -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper +from .raw_client import AsyncRawAuthenticationClient, RawAuthenticationClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +13,18 @@ class AuthenticationClient: def __init__(self, *, client_wrapper: SyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = RawAuthenticationClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawAuthenticationClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawAuthenticationClient + """ + return self._raw_client def authentication_service_get_auth_token( self, @@ -65,80 +71,35 @@ def authentication_service_get_auth_token( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.authentication.authentication_service_get_auth_token( - grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer", - assertion="eyLhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNzIjoiY29tcGFueSIsImV4cCI6MTYxNTE5MzgwNywiaWF0IjoxNjE1MTY1MDQwLCJhdWQiOiKzb21lYXVkaWVuY2UifQ.4pcPyMDQ9o1PSyXnrXCjTwXyr4BSezdI1AVTmud2fU3", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.authentication.authentication_service_get_auth_token(grant_type='urn:ietf:params:oauth:grant-type:jwt-bearer', assertion='eyLhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNzIjoiY29tcGFueSIsImV4cCI6MTYxNTE5MzgwNywiaWF0IjoxNjE1MTY1MDQwLCJhdWQiOiKzb21lYXVkaWVuY2UifQ.4pcPyMDQ9o1PSyXnrXCjTwXyr4BSezdI1AVTmud2fU3', ) """ - _response = self._client_wrapper.httpx_client.request( - "v1/auth/sa/oauth/token", - method="POST", - json={ - "grant_type": grant_type, - "assertion": assertion, - "subject_token": subject_token, - "subject_token_type": subject_token_type, - "requested_token_use": requested_token_use, - "scope": scope, - }, - headers={ - "content-type": "application/json", - }, + _response = self._raw_client.authentication_service_get_auth_token( + grant_type=grant_type, + assertion=assertion, + subject_token=subject_token, + subject_token_type=subject_token_type, + requested_token_use=requested_token_use, + scope=scope, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1GetAuthTokenResponse, - parse_obj_as( - type_=V1GetAuthTokenResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 400: - raise BadRequestError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - if _response.status_code == 401: - raise UnauthorizedError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data class AsyncAuthenticationClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = AsyncRawAuthenticationClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawAuthenticationClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawAuthenticationClient + """ + return self._raw_client async def authentication_service_get_auth_token( self, @@ -184,81 +145,20 @@ async def authentication_service_get_auth_token( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.authentication.authentication_service_get_auth_token( - grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer", - assertion="eyLhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNzIjoiY29tcGFueSIsImV4cCI6MTYxNTE5MzgwNywiaWF0IjoxNjE1MTY1MDQwLCJhdWQiOiKzb21lYXVkaWVuY2UifQ.4pcPyMDQ9o1PSyXnrXCjTwXyr4BSezdI1AVTmud2fU3", - ) - - + await client.authentication.authentication_service_get_auth_token(grant_type='urn:ietf:params:oauth:grant-type:jwt-bearer', assertion='eyLhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNzIjoiY29tcGFueSIsImV4cCI6MTYxNTE5MzgwNywiaWF0IjoxNjE1MTY1MDQwLCJhdWQiOiKzb21lYXVkaWVuY2UifQ.4pcPyMDQ9o1PSyXnrXCjTwXyr4BSezdI1AVTmud2fU3', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - "v1/auth/sa/oauth/token", - method="POST", - json={ - "grant_type": grant_type, - "assertion": assertion, - "subject_token": subject_token, - "subject_token_type": subject_token_type, - "requested_token_use": requested_token_use, - "scope": scope, - }, - headers={ - "content-type": "application/json", - }, + _response = await self._raw_client.authentication_service_get_auth_token( + grant_type=grant_type, + assertion=assertion, + subject_token=subject_token, + subject_token_type=subject_token_type, + requested_token_use=requested_token_use, + scope=scope, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1GetAuthTokenResponse, - parse_obj_as( - type_=V1GetAuthTokenResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 400: - raise BadRequestError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - if _response.status_code == 401: - raise UnauthorizedError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data diff --git a/skyflow/generated/rest/authentication/raw_client.py b/skyflow/generated/rest/authentication/raw_client.py new file mode 100644 index 00000000..0c2778c2 --- /dev/null +++ b/skyflow/generated/rest/authentication/raw_client.py @@ -0,0 +1,235 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..errors.bad_request_error import BadRequestError +from ..errors.not_found_error import NotFoundError +from ..errors.unauthorized_error import UnauthorizedError +from ..types.v_1_get_auth_token_response import V1GetAuthTokenResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawAuthenticationClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def authentication_service_get_auth_token( + self, + *, + grant_type: str, + assertion: str, + subject_token: typing.Optional[str] = OMIT, + subject_token_type: typing.Optional[str] = OMIT, + requested_token_use: typing.Optional[str] = OMIT, + scope: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1GetAuthTokenResponse]: + """ +

Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the Authorization header.

Note: For recommended ways to authenticate, see API authentication.

+ + Parameters + ---------- + grant_type : str + Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`. + + assertion : str + User-signed JWT token that contains the following fields:
  • iss: Issuer of the JWT.
  • key: Unique identifier for the key.
  • aud: Recipient the JWT is intended for.
  • exp: Time the JWT expires.
  • sub: Subject of the JWT.
  • ctx: (Optional) Value for Context-aware authorization.
+ + subject_token : typing.Optional[str] + Subject token. + + subject_token_type : typing.Optional[str] + Subject token type. + + requested_token_use : typing.Optional[str] + Token use type. Either `delegation` or `impersonation`. + + scope : typing.Optional[str] + Subset of available roles to associate with the requested token. Uses the format "role:\ role:\". + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1GetAuthTokenResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + "v1/auth/sa/oauth/token", + method="POST", + json={ + "grant_type": grant_type, + "assertion": assertion, + "subject_token": subject_token, + "subject_token_type": subject_token_type, + "requested_token_use": requested_token_use, + "scope": scope, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1GetAuthTokenResponse, + parse_obj_as( + type_=V1GetAuthTokenResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 401: + raise UnauthorizedError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + +class AsyncRawAuthenticationClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def authentication_service_get_auth_token( + self, + *, + grant_type: str, + assertion: str, + subject_token: typing.Optional[str] = OMIT, + subject_token_type: typing.Optional[str] = OMIT, + requested_token_use: typing.Optional[str] = OMIT, + scope: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1GetAuthTokenResponse]: + """ +

Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the Authorization header.

Note: For recommended ways to authenticate, see API authentication.

+ + Parameters + ---------- + grant_type : str + Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`. + + assertion : str + User-signed JWT token that contains the following fields:
  • iss: Issuer of the JWT.
  • key: Unique identifier for the key.
  • aud: Recipient the JWT is intended for.
  • exp: Time the JWT expires.
  • sub: Subject of the JWT.
  • ctx: (Optional) Value for Context-aware authorization.
+ + subject_token : typing.Optional[str] + Subject token. + + subject_token_type : typing.Optional[str] + Subject token type. + + requested_token_use : typing.Optional[str] + Token use type. Either `delegation` or `impersonation`. + + scope : typing.Optional[str] + Subset of available roles to associate with the requested token. Uses the format "role:\ role:\". + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1GetAuthTokenResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + "v1/auth/sa/oauth/token", + method="POST", + json={ + "grant_type": grant_type, + "assertion": assertion, + "subject_token": subject_token, + "subject_token_type": subject_token_type, + "requested_token_use": requested_token_use, + "scope": scope, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1GetAuthTokenResponse, + parse_obj_as( + type_=V1GetAuthTokenResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 401: + raise UnauthorizedError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/bin_lookup/__init__.py b/skyflow/generated/rest/bin_lookup/__init__.py index f3ea2659..5cde0202 100644 --- a/skyflow/generated/rest/bin_lookup/__init__.py +++ b/skyflow/generated/rest/bin_lookup/__init__.py @@ -1,2 +1,4 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + diff --git a/skyflow/generated/rest/bin_lookup/client.py b/skyflow/generated/rest/bin_lookup/client.py index 58d30c51..a217ae60 100644 --- a/skyflow/generated/rest/bin_lookup/client.py +++ b/skyflow/generated/rest/bin_lookup/client.py @@ -1,16 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing -from ..core.client_wrapper import SyncClientWrapper -from ..types.v_1_vault_schema_config import V1VaultSchemaConfig + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.request_options import RequestOptions from ..types.v_1_bin_list_response import V1BinListResponse -from ..core.serialization import convert_and_respect_annotation_metadata -from ..core.pydantic_utilities import parse_obj_as -from ..errors.not_found_error import NotFoundError -from json.decoder import JSONDecodeError -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper +from ..types.v_1_vault_schema_config import V1VaultSchemaConfig +from .raw_client import AsyncRawBinLookupClient, RawBinLookupClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +14,18 @@ class BinLookupClient: def __init__(self, *, client_wrapper: SyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = RawBinLookupClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawBinLookupClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawBinLookupClient + """ + return self._raw_client def bin_list_service_list_cards_of_bin( self, @@ -56,59 +63,33 @@ def bin_list_service_list_cards_of_bin( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.bin_lookup.bin_list_service_list_cards_of_bin( - bin="012345", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.bin_lookup.bin_list_service_list_cards_of_bin(bin='012345', ) """ - _response = self._client_wrapper.httpx_client.request( - "v1/card_lookup", - method="POST", - json={ - "fields": fields, - "BIN": bin, - "vault_schema_config": convert_and_respect_annotation_metadata( - object_=vault_schema_config, annotation=V1VaultSchemaConfig, direction="write" - ), - "skyflow_id": skyflow_id, - }, - headers={ - "content-type": "application/json", - }, + _response = self._raw_client.bin_list_service_list_cards_of_bin( + fields=fields, + bin=bin, + vault_schema_config=vault_schema_config, + skyflow_id=skyflow_id, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BinListResponse, - parse_obj_as( - type_=V1BinListResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data class AsyncBinLookupClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = AsyncRawBinLookupClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawBinLookupClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawBinLookupClient + """ + return self._raw_client async def bin_list_service_list_cards_of_bin( self, @@ -145,60 +126,18 @@ async def bin_list_service_list_cards_of_bin( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.bin_lookup.bin_list_service_list_cards_of_bin( - bin="012345", - ) - - + await client.bin_lookup.bin_list_service_list_cards_of_bin(bin='012345', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - "v1/card_lookup", - method="POST", - json={ - "fields": fields, - "BIN": bin, - "vault_schema_config": convert_and_respect_annotation_metadata( - object_=vault_schema_config, annotation=V1VaultSchemaConfig, direction="write" - ), - "skyflow_id": skyflow_id, - }, - headers={ - "content-type": "application/json", - }, + _response = await self._raw_client.bin_list_service_list_cards_of_bin( + fields=fields, + bin=bin, + vault_schema_config=vault_schema_config, + skyflow_id=skyflow_id, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BinListResponse, - parse_obj_as( - type_=V1BinListResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data diff --git a/skyflow/generated/rest/bin_lookup/raw_client.py b/skyflow/generated/rest/bin_lookup/raw_client.py new file mode 100644 index 00000000..c021d684 --- /dev/null +++ b/skyflow/generated/rest/bin_lookup/raw_client.py @@ -0,0 +1,177 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..core.serialization import convert_and_respect_annotation_metadata +from ..errors.not_found_error import NotFoundError +from ..types.v_1_bin_list_response import V1BinListResponse +from ..types.v_1_vault_schema_config import V1VaultSchemaConfig + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawBinLookupClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def bin_list_service_list_cards_of_bin( + self, + *, + fields: typing.Optional[typing.Sequence[str]] = OMIT, + bin: typing.Optional[str] = OMIT, + vault_schema_config: typing.Optional[V1VaultSchemaConfig] = OMIT, + skyflow_id: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1BinListResponse]: + """ + Note: This endpoint is in beta and subject to change.

Returns the specified card metadata. + + Parameters + ---------- + fields : typing.Optional[typing.Sequence[str]] + Fields to return. If not specified, all fields are returned. + + bin : typing.Optional[str] + BIN of the card. + + vault_schema_config : typing.Optional[V1VaultSchemaConfig] + + skyflow_id : typing.Optional[str] + skyflow_id of the record. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1BinListResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + "v1/card_lookup", + method="POST", + json={ + "fields": fields, + "BIN": bin, + "vault_schema_config": convert_and_respect_annotation_metadata( + object_=vault_schema_config, annotation=V1VaultSchemaConfig, direction="write" + ), + "skyflow_id": skyflow_id, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BinListResponse, + parse_obj_as( + type_=V1BinListResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + +class AsyncRawBinLookupClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def bin_list_service_list_cards_of_bin( + self, + *, + fields: typing.Optional[typing.Sequence[str]] = OMIT, + bin: typing.Optional[str] = OMIT, + vault_schema_config: typing.Optional[V1VaultSchemaConfig] = OMIT, + skyflow_id: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1BinListResponse]: + """ + Note: This endpoint is in beta and subject to change.

Returns the specified card metadata. + + Parameters + ---------- + fields : typing.Optional[typing.Sequence[str]] + Fields to return. If not specified, all fields are returned. + + bin : typing.Optional[str] + BIN of the card. + + vault_schema_config : typing.Optional[V1VaultSchemaConfig] + + skyflow_id : typing.Optional[str] + skyflow_id of the record. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1BinListResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + "v1/card_lookup", + method="POST", + json={ + "fields": fields, + "BIN": bin, + "vault_schema_config": convert_and_respect_annotation_metadata( + object_=vault_schema_config, annotation=V1VaultSchemaConfig, direction="write" + ), + "skyflow_id": skyflow_id, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BinListResponse, + parse_obj_as( + type_=V1BinListResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/client.py b/skyflow/generated/rest/client.py index 7064d444..3dab76fb 100644 --- a/skyflow/generated/rest/client.py +++ b/skyflow/generated/rest/client.py @@ -1,22 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import typing -from .environment import SkyflowEnvironment + import httpx -from .core.client_wrapper import SyncClientWrapper -from .audit.client import AuditClient -from .bin_lookup.client import BinLookupClient -from .records.client import RecordsClient -from .tokens.client import TokensClient -from .query.client import QueryClient -from .authentication.client import AuthenticationClient -from .core.client_wrapper import AsyncClientWrapper -from .audit.client import AsyncAuditClient -from .bin_lookup.client import AsyncBinLookupClient -from .records.client import AsyncRecordsClient -from .tokens.client import AsyncTokensClient -from .query.client import AsyncQueryClient -from .authentication.client import AsyncAuthenticationClient +from .audit.client import AsyncAuditClient, AuditClient +from .authentication.client import AsyncAuthenticationClient, AuthenticationClient +from .bin_lookup.client import AsyncBinLookupClient, BinLookupClient +from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .environment import SkyflowEnvironment +from .query.client import AsyncQueryClient, QueryClient +from .records.client import AsyncRecordsClient, RecordsClient +from .tokens.client import AsyncTokensClient, TokensClient class Skyflow: @@ -31,8 +25,6 @@ class Skyflow: environment : SkyflowEnvironment The environment to use for requests from the client. from .environment import SkyflowEnvironment - - Defaults to SkyflowEnvironment.PRODUCTION @@ -50,10 +42,7 @@ class Skyflow: Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) + client = Skyflow(token="YOUR_TOKEN", ) """ def __init__( @@ -66,7 +55,9 @@ def __init__( follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else httpx_client.timeout.read + ) self._client_wrapper = SyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, @@ -97,8 +88,6 @@ class AsyncSkyflow: environment : SkyflowEnvironment The environment to use for requests from the client. from .environment import SkyflowEnvironment - - Defaults to SkyflowEnvironment.PRODUCTION @@ -116,10 +105,7 @@ class AsyncSkyflow: Examples -------- from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) + client = AsyncSkyflow(token="YOUR_TOKEN", ) """ def __init__( @@ -132,7 +118,9 @@ def __init__( follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else httpx_client.timeout.read + ) self._client_wrapper = AsyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, diff --git a/skyflow/generated/rest/core/__init__.py b/skyflow/generated/rest/core/__init__.py index f03aecbf..31bbb818 100644 --- a/skyflow/generated/rest/core/__init__.py +++ b/skyflow/generated/rest/core/__init__.py @@ -1,10 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .api_error import ApiError from .client_wrapper import AsyncClientWrapper, BaseClientWrapper, SyncClientWrapper from .datetime_utils import serialize_datetime from .file import File, convert_file_dict_to_httpx_tuples, with_content_type from .http_client import AsyncHttpClient, HttpClient +from .http_response import AsyncHttpResponse, HttpResponse from .jsonable_encoder import jsonable_encoder from .pydantic_utilities import ( IS_PYDANTIC_V2, @@ -24,10 +27,12 @@ "ApiError", "AsyncClientWrapper", "AsyncHttpClient", + "AsyncHttpResponse", "BaseClientWrapper", "FieldMetadata", "File", "HttpClient", + "HttpResponse", "IS_PYDANTIC_V2", "RequestOptions", "SyncClientWrapper", diff --git a/skyflow/generated/rest/core/api_error.py b/skyflow/generated/rest/core/api_error.py index 2e9fc543..6f850a60 100644 --- a/skyflow/generated/rest/core/api_error.py +++ b/skyflow/generated/rest/core/api_error.py @@ -1,15 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import typing +from typing import Any, Dict, Optional class ApiError(Exception): - status_code: typing.Optional[int] - body: typing.Any + headers: Optional[Dict[str, str]] + status_code: Optional[int] + body: Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, + *, + headers: Optional[Dict[str, str]] = None, + status_code: Optional[int] = None, + body: Any = None, + ) -> None: + self.headers = headers self.status_code = status_code self.body = body def __str__(self) -> str: - return f"status_code: {self.status_code}, body: {self.body}" + return f"headers: {self.headers}, status_code: {self.status_code}, body: {self.body}" diff --git a/skyflow/generated/rest/core/client_wrapper.py b/skyflow/generated/rest/core/client_wrapper.py index 7177cf7c..2c55b8d9 100644 --- a/skyflow/generated/rest/core/client_wrapper.py +++ b/skyflow/generated/rest/core/client_wrapper.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing + import httpx -from .http_client import HttpClient -from .http_client import AsyncHttpClient +from .http_client import AsyncHttpClient, HttpClient class BaseClientWrapper: @@ -21,8 +21,8 @@ def __init__( def get_headers(self) -> typing.Dict[str, str]: headers: typing.Dict[str, str] = { "X-Fern-Language": "Python", - "X-Fern-SDK-Name": "skyflow", - "X-Fern-SDK-Version": "1.15.2", + "X-Fern-SDK-Name": "skyflow.generated.rest", + "X-Fern-SDK-Version": "0.0.163", } headers["Authorization"] = f"Bearer {self._get_token()}" return headers diff --git a/skyflow/generated/rest/core/http_client.py b/skyflow/generated/rest/core/http_client.py index 275a54cc..e7bd4f79 100644 --- a/skyflow/generated/rest/core/http_client.py +++ b/skyflow/generated/rest/core/http_client.py @@ -2,7 +2,6 @@ import asyncio import email.utils -import json import re import time import typing @@ -11,7 +10,6 @@ from random import random import httpx - from .file import File, convert_file_dict_to_httpx_tuples from .jsonable_encoder import jsonable_encoder from .query_encoder import encode_query diff --git a/skyflow/generated/rest/core/http_response.py b/skyflow/generated/rest/core/http_response.py new file mode 100644 index 00000000..48a1798a --- /dev/null +++ b/skyflow/generated/rest/core/http_response.py @@ -0,0 +1,55 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Dict, Generic, TypeVar + +import httpx + +T = TypeVar("T") +"""Generic to represent the underlying type of the data wrapped by the HTTP response.""" + + +class BaseHttpResponse: + """Minimalist HTTP response wrapper that exposes response headers.""" + + _response: httpx.Response + + def __init__(self, response: httpx.Response): + self._response = response + + @property + def headers(self) -> Dict[str, str]: + return dict(self._response.headers) + + +class HttpResponse(Generic[T], BaseHttpResponse): + """HTTP response wrapper that exposes response headers and data.""" + + _data: T + + def __init__(self, response: httpx.Response, data: T): + super().__init__(response) + self._data = data + + @property + def data(self) -> T: + return self._data + + def close(self) -> None: + self._response.close() + + +class AsyncHttpResponse(Generic[T], BaseHttpResponse): + """HTTP response wrapper that exposes response headers and data.""" + + _data: T + + def __init__(self, response: httpx.Response, data: T): + super().__init__(response) + self._data = data + + @property + def data(self) -> T: + return self._data + + async def close(self) -> None: + await self._response.aclose() diff --git a/skyflow/generated/rest/core/jsonable_encoder.py b/skyflow/generated/rest/core/jsonable_encoder.py index 1b631e90..afee3662 100644 --- a/skyflow/generated/rest/core/jsonable_encoder.py +++ b/skyflow/generated/rest/core/jsonable_encoder.py @@ -17,7 +17,6 @@ from typing import Any, Callable, Dict, List, Optional, Set, Union import pydantic - from .datetime_utils import serialize_datetime from .pydantic_utilities import ( IS_PYDANTIC_V2, diff --git a/skyflow/generated/rest/core/pydantic_utilities.py b/skyflow/generated/rest/core/pydantic_utilities.py index ca1f4792..60a2c713 100644 --- a/skyflow/generated/rest/core/pydantic_utilities.py +++ b/skyflow/generated/rest/core/pydantic_utilities.py @@ -2,89 +2,65 @@ # nopycln: file import datetime as dt -import typing from collections import defaultdict - -import typing_extensions +from typing import Any, Callable, ClassVar, Dict, List, Mapping, Optional, Set, Tuple, Type, TypeVar, Union, cast import pydantic -from .datetime_utils import serialize_datetime -from .serialization import convert_and_respect_annotation_metadata - IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.") if IS_PYDANTIC_V2: - # isort will try to reformat the comments on these imports, which breaks mypy - # isort: off - from pydantic.v1.datetime_parse import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 - parse_date as parse_date, - ) - from pydantic.v1.datetime_parse import ( # pyright: ignore[reportMissingImports] # Pydantic v2 - parse_datetime as parse_datetime, - ) - from pydantic.v1.json import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 - ENCODERS_BY_TYPE as encoders_by_type, - ) - from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 - get_args as get_args, - ) - from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 - get_origin as get_origin, - ) - from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 - is_literal_type as is_literal_type, - ) - from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 - is_union as is_union, - ) - from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.datetime_parse import parse_date as parse_date + from pydantic.v1.datetime_parse import parse_datetime as parse_datetime + from pydantic.v1.fields import ModelField as ModelField + from pydantic.v1.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[attr-defined] + from pydantic.v1.typing import get_args as get_args + from pydantic.v1.typing import get_origin as get_origin + from pydantic.v1.typing import is_literal_type as is_literal_type + from pydantic.v1.typing import is_union as is_union else: - from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 - from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore # Pydantic v1 - from pydantic.fields import ModelField as ModelField # type: ignore # Pydantic v1 - from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore # Pydantic v1 - from pydantic.typing import get_args as get_args # type: ignore # Pydantic v1 - from pydantic.typing import get_origin as get_origin # type: ignore # Pydantic v1 - from pydantic.typing import is_literal_type as is_literal_type # type: ignore # Pydantic v1 - from pydantic.typing import is_union as is_union # type: ignore # Pydantic v1 - - # isort: on + from pydantic.datetime_parse import parse_date as parse_date # type: ignore[no-redef] + from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore[no-redef] + from pydantic.fields import ModelField as ModelField # type: ignore[attr-defined, no-redef] + from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[no-redef] + from pydantic.typing import get_args as get_args # type: ignore[no-redef] + from pydantic.typing import get_origin as get_origin # type: ignore[no-redef] + from pydantic.typing import is_literal_type as is_literal_type # type: ignore[no-redef] + from pydantic.typing import is_union as is_union # type: ignore[no-redef] +from .datetime_utils import serialize_datetime +from .serialization import convert_and_respect_annotation_metadata +from typing_extensions import TypeAlias -T = typing.TypeVar("T") -Model = typing.TypeVar("Model", bound=pydantic.BaseModel) +T = TypeVar("T") +Model = TypeVar("Model", bound=pydantic.BaseModel) -def parse_obj_as(type_: typing.Type[T], object_: typing.Any) -> T: +def parse_obj_as(type_: Type[T], object_: Any) -> T: dealiased_object = convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read") if IS_PYDANTIC_V2: - adapter = pydantic.TypeAdapter(type_) # type: ignore # Pydantic v2 + adapter = pydantic.TypeAdapter(type_) # type: ignore[attr-defined] return adapter.validate_python(dealiased_object) - else: - return pydantic.parse_obj_as(type_, dealiased_object) + return pydantic.parse_obj_as(type_, dealiased_object) -def to_jsonable_with_fallback( - obj: typing.Any, fallback_serializer: typing.Callable[[typing.Any], typing.Any] -) -> typing.Any: +def to_jsonable_with_fallback(obj: Any, fallback_serializer: Callable[[Any], Any]) -> Any: if IS_PYDANTIC_V2: from pydantic_core import to_jsonable_python return to_jsonable_python(obj, fallback=fallback_serializer) - else: - return fallback_serializer(obj) + return fallback_serializer(obj) class UniversalBaseModel(pydantic.BaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + model_config: ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( # type: ignore[typeddict-unknown-key] # Allow fields beginning with `model_` to be used in the model protected_namespaces=(), - ) # type: ignore # Pydantic v2 + ) - @pydantic.model_serializer(mode="wrap", when_used="json") # type: ignore # Pydantic v2 - def serialize_model(self, handler: pydantic.SerializerFunctionWrapHandler) -> typing.Any: # type: ignore # Pydantic v2 + @pydantic.model_serializer(mode="wrap", when_used="json") # type: ignore[attr-defined] + def serialize_model(self, handler: pydantic.SerializerFunctionWrapHandler) -> Any: # type: ignore[name-defined] serialized = handler(self) data = {k: serialize_datetime(v) if isinstance(v, dt.datetime) else v for k, v in serialized.items()} return data @@ -96,34 +72,28 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} @classmethod - def model_construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any - ) -> "Model": + def model_construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model": dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read") return cls.construct(_fields_set, **dealiased_object) @classmethod - def construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any - ) -> "Model": + def construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model": dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read") if IS_PYDANTIC_V2: - return super().model_construct(_fields_set, **dealiased_object) # type: ignore # Pydantic v2 - else: - return super().construct(_fields_set, **dealiased_object) + return super().model_construct(_fields_set, **dealiased_object) # type: ignore[misc] + return super().construct(_fields_set, **dealiased_object) - def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = { + def json(self, **kwargs: Any) -> str: + kwargs_with_defaults = { "by_alias": True, "exclude_unset": True, **kwargs, } if IS_PYDANTIC_V2: - return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 - else: - return super().json(**kwargs_with_defaults) + return super().model_dump_json(**kwargs_with_defaults) # type: ignore[misc] + return super().json(**kwargs_with_defaults) - def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: + def dict(self, **kwargs: Any) -> Dict[str, Any]: """ Override the default dict method to `exclude_unset` by default. This function patches `exclude_unset` to work include fields within non-None default values. @@ -134,21 +104,21 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: # We'd ideally do the same for Pydantic V2, but it shells out to a library to serialize models # that we have less control over, and this is less intrusive than custom serializers for now. if IS_PYDANTIC_V2: - kwargs_with_defaults_exclude_unset: typing.Any = { + kwargs_with_defaults_exclude_unset = { **kwargs, "by_alias": True, "exclude_unset": True, "exclude_none": False, } - kwargs_with_defaults_exclude_none: typing.Any = { + kwargs_with_defaults_exclude_none = { **kwargs, "by_alias": True, "exclude_none": True, "exclude_unset": False, } dict_dump = deep_union_pydantic_dicts( - super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore # Pydantic v2 - super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore # Pydantic v2 + super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore[misc] + super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore[misc] ) else: @@ -168,7 +138,7 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: if default is not None: self.__fields_set__.add(name) - kwargs_with_defaults_exclude_unset_include_fields: typing.Any = { + kwargs_with_defaults_exclude_unset_include_fields = { "by_alias": True, "exclude_unset": True, "include": _fields_set, @@ -180,12 +150,10 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: return convert_and_respect_annotation_metadata(object_=dict_dump, annotation=self.__class__, direction="write") -def _union_list_of_pydantic_dicts( - source: typing.List[typing.Any], destination: typing.List[typing.Any] -) -> typing.List[typing.Any]: - converted_list: typing.List[typing.Any] = [] +def _union_list_of_pydantic_dicts(source: List[Any], destination: List[Any]) -> List[Any]: + converted_list: List[Any] = [] for i, item in enumerate(source): - destination_value = destination[i] # type: ignore + destination_value = destination[i] if isinstance(item, dict): converted_list.append(deep_union_pydantic_dicts(item, destination_value)) elif isinstance(item, list): @@ -195,9 +163,7 @@ def _union_list_of_pydantic_dicts( return converted_list -def deep_union_pydantic_dicts( - source: typing.Dict[str, typing.Any], destination: typing.Dict[str, typing.Any] -) -> typing.Dict[str, typing.Any]: +def deep_union_pydantic_dicts(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]: for key, value in source.items(): node = destination.setdefault(key, {}) if isinstance(value, dict): @@ -215,18 +181,16 @@ def deep_union_pydantic_dicts( if IS_PYDANTIC_V2: - class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore # Pydantic v2 + class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore[name-defined, type-arg] pass - UniversalRootModel: typing_extensions.TypeAlias = V2RootModel # type: ignore + UniversalRootModel: TypeAlias = V2RootModel # type: ignore[misc] else: - UniversalRootModel: typing_extensions.TypeAlias = UniversalBaseModel # type: ignore + UniversalRootModel: TypeAlias = UniversalBaseModel # type: ignore[misc, no-redef] -def encode_by_type(o: typing.Any) -> typing.Any: - encoders_by_class_tuples: typing.Dict[typing.Callable[[typing.Any], typing.Any], typing.Tuple[typing.Any, ...]] = ( - defaultdict(tuple) - ) +def encode_by_type(o: Any) -> Any: + encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple) for type_, encoder in encoders_by_type.items(): encoders_by_class_tuples[encoder] += (type_,) @@ -237,54 +201,49 @@ def encode_by_type(o: typing.Any) -> typing.Any: return encoder(o) -def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> None: +def update_forward_refs(model: Type["Model"], **localns: Any) -> None: if IS_PYDANTIC_V2: - model.model_rebuild(raise_errors=False) # type: ignore # Pydantic v2 + model.model_rebuild(raise_errors=False) # type: ignore[attr-defined] else: model.update_forward_refs(**localns) # Mirrors Pydantic's internal typing -AnyCallable = typing.Callable[..., typing.Any] +AnyCallable = Callable[..., Any] def universal_root_validator( pre: bool = False, -) -> typing.Callable[[AnyCallable], AnyCallable]: +) -> Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: if IS_PYDANTIC_V2: - return pydantic.model_validator(mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 - else: - return pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 + return cast(AnyCallable, pydantic.model_validator(mode="before" if pre else "after")(func)) # type: ignore[attr-defined] + return cast(AnyCallable, pydantic.root_validator(pre=pre)(func)) # type: ignore[call-overload] return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator(field_name: str, pre: bool = False) -> Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: if IS_PYDANTIC_V2: - return pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 - else: - return pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 + return cast(AnyCallable, pydantic.field_validator(field_name, mode="before" if pre else "after")(func)) # type: ignore[attr-defined] + return cast(AnyCallable, pydantic.validator(field_name, pre=pre)(func)) return decorator -PydanticField = typing.Union[ModelField, pydantic.fields.FieldInfo] +PydanticField = Union[ModelField, pydantic.fields.FieldInfo] -def _get_model_fields( - model: typing.Type["Model"], -) -> typing.Mapping[str, PydanticField]: +def _get_model_fields(model: Type["Model"]) -> Mapping[str, PydanticField]: if IS_PYDANTIC_V2: - return model.model_fields # type: ignore # Pydantic v2 - else: - return model.__fields__ # type: ignore # Pydantic v1 + return cast(Mapping[str, PydanticField], model.model_fields) # type: ignore[attr-defined] + return cast(Mapping[str, PydanticField], model.__fields__) -def _get_field_default(field: PydanticField) -> typing.Any: +def _get_field_default(field: PydanticField) -> Any: try: - value = field.get_default() # type: ignore # Pydantic < v1.10.15 + value = field.get_default() # type: ignore[union-attr] except: value = field.default if IS_PYDANTIC_V2: diff --git a/skyflow/generated/rest/core/serialization.py b/skyflow/generated/rest/core/serialization.py index cb5dcbf9..c36e865c 100644 --- a/skyflow/generated/rest/core/serialization.py +++ b/skyflow/generated/rest/core/serialization.py @@ -4,9 +4,8 @@ import inspect import typing -import typing_extensions - import pydantic +import typing_extensions class FieldMetadata: @@ -161,7 +160,12 @@ def _convert_mapping( direction: typing.Literal["read", "write"], ) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} - annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) + try: + annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) + except NameError: + # The TypedDict contains a circular reference, so + # we use the __annotations__ attribute directly. + annotations = getattr(expected_type, "__annotations__", {}) aliases_to_field_names = _get_alias_to_field_name(annotations) for key, value in object_.items(): if direction == "read" and key in aliases_to_field_names: diff --git a/skyflow/generated/rest/errors/__init__.py b/skyflow/generated/rest/errors/__init__.py index 64f898f5..fdf6196c 100644 --- a/skyflow/generated/rest/errors/__init__.py +++ b/skyflow/generated/rest/errors/__init__.py @@ -1,5 +1,7 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .bad_request_error import BadRequestError from .not_found_error import NotFoundError from .unauthorized_error import UnauthorizedError diff --git a/skyflow/generated/rest/errors/bad_request_error.py b/skyflow/generated/rest/errors/bad_request_error.py index 2f3dba61..5f24fa6d 100644 --- a/skyflow/generated/rest/errors/bad_request_error.py +++ b/skyflow/generated/rest/errors/bad_request_error.py @@ -1,8 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.api_error import ApiError import typing +from ..core.api_error import ApiError + class BadRequestError(ApiError): def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): diff --git a/skyflow/generated/rest/errors/not_found_error.py b/skyflow/generated/rest/errors/not_found_error.py index b557be0a..68977121 100644 --- a/skyflow/generated/rest/errors/not_found_error.py +++ b/skyflow/generated/rest/errors/not_found_error.py @@ -1,8 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.api_error import ApiError import typing +from ..core.api_error import ApiError + class NotFoundError(ApiError): def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): diff --git a/skyflow/generated/rest/errors/unauthorized_error.py b/skyflow/generated/rest/errors/unauthorized_error.py index 6d01cc9f..cd97f14d 100644 --- a/skyflow/generated/rest/errors/unauthorized_error.py +++ b/skyflow/generated/rest/errors/unauthorized_error.py @@ -1,8 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.api_error import ApiError import typing +from ..core.api_error import ApiError + class UnauthorizedError(ApiError): def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): diff --git a/skyflow/generated/rest/query/__init__.py b/skyflow/generated/rest/query/__init__.py index f3ea2659..5cde0202 100644 --- a/skyflow/generated/rest/query/__init__.py +++ b/skyflow/generated/rest/query/__init__.py @@ -1,2 +1,4 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + diff --git a/skyflow/generated/rest/query/client.py b/skyflow/generated/rest/query/client.py index cf3ca319..1f5edd75 100644 --- a/skyflow/generated/rest/query/client.py +++ b/skyflow/generated/rest/query/client.py @@ -1,15 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing -from ..core.client_wrapper import SyncClientWrapper + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.request_options import RequestOptions from ..types.v_1_get_query_response import V1GetQueryResponse -from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as -from ..errors.not_found_error import NotFoundError -from json.decoder import JSONDecodeError -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper +from .raw_client import AsyncRawQueryClient, RawQueryClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +13,18 @@ class QueryClient: def __init__(self, *, client_wrapper: SyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = RawQueryClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawQueryClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawQueryClient + """ + return self._raw_client def query_service_execute_query( self, @@ -48,55 +55,27 @@ def query_service_execute_query( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.query.query_service_execute_query( - vault_id="vaultID", - query='select * from opportunities where id="01010000ade21cded569d43944544ec6"', - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.query.query_service_execute_query(vault_id='vaultID', query='select * from opportunities where id="01010000ade21cded569d43944544ec6"', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/query", - method="POST", - json={ - "query": query, - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, - ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1GetQueryResponse, - parse_obj_as( - type_=V1GetQueryResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + _response = self._raw_client.query_service_execute_query(vault_id, query=query, request_options=request_options) + return _response.data class AsyncQueryClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = AsyncRawQueryClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawQueryClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawQueryClient + """ + return self._raw_client async def query_service_execute_query( self, @@ -126,56 +105,14 @@ async def query_service_execute_query( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.query.query_service_execute_query( - vault_id="vaultID", - query='select * from opportunities where id="01010000ade21cded569d43944544ec6"', - ) - - + await client.query.query_service_execute_query(vault_id='vaultID', query='select * from opportunities where id="01010000ade21cded569d43944544ec6"', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/query", - method="POST", - json={ - "query": query, - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, + _response = await self._raw_client.query_service_execute_query( + vault_id, query=query, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1GetQueryResponse, - parse_obj_as( - type_=V1GetQueryResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data diff --git a/skyflow/generated/rest/query/raw_client.py b/skyflow/generated/rest/query/raw_client.py new file mode 100644 index 00000000..b6a201a1 --- /dev/null +++ b/skyflow/generated/rest/query/raw_client.py @@ -0,0 +1,152 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..errors.not_found_error import NotFoundError +from ..types.v_1_get_query_response import V1GetQueryResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawQueryClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def query_service_execute_query( + self, + vault_id: str, + *, + query: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1GetQueryResponse]: + """ + Returns records for a valid SQL query. This endpoint
  • Can return redacted record values.
  • Supports only the SELECT command.
  • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
  • Can't modify the vault or perform transactions.
  • Can't return tokens.
  • Can't return file download or render URLs.
  • Doesn't support the WHERE keyword with columns using transient tokenization.
  • Doesn't support `?` conditional for columns with column-level encryption disabled.
    • + + Parameters + ---------- + vault_id : str + ID of the vault. + + query : typing.Optional[str] + The SQL query to execute.

      Supported commands:
      • SELECT
      Supported operators:
      • >
      • <
      • =
      • AND
      • OR
      • NOT
      • LIKE
      • ILIKE
      • NULL
      • NOT NULL
      Supported keywords:
      • FROM
      • JOIN
      • INNER JOIN
      • LEFT OUTER JOIN
      • LEFT JOIN
      • RIGHT OUTER JOIN
      • RIGHT JOIN
      • FULL OUTER JOIN
      • FULL JOIN
      • OFFSET
      • LIMIT
      • WHERE
      Supported functions:
      • AVG()
      • SUM()
      • COUNT()
      • MIN()
      • MAX()
      • REDACTION()
      + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1GetQueryResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/query", + method="POST", + json={ + "query": query, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1GetQueryResponse, + parse_obj_as( + type_=V1GetQueryResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + +class AsyncRawQueryClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def query_service_execute_query( + self, + vault_id: str, + *, + query: typing.Optional[str] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1GetQueryResponse]: + """ + Returns records for a valid SQL query. This endpoint
      • Can return redacted record values.
      • Supports only the SELECT command.
      • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
      • Can't modify the vault or perform transactions.
      • Can't return tokens.
      • Can't return file download or render URLs.
      • Doesn't support the WHERE keyword with columns using transient tokenization.
      • Doesn't support `?` conditional for columns with column-level encryption disabled.
        • + + Parameters + ---------- + vault_id : str + ID of the vault. + + query : typing.Optional[str] + The SQL query to execute.

          Supported commands:
          • SELECT
          Supported operators:
          • >
          • <
          • =
          • AND
          • OR
          • NOT
          • LIKE
          • ILIKE
          • NULL
          • NOT NULL
          Supported keywords:
          • FROM
          • JOIN
          • INNER JOIN
          • LEFT OUTER JOIN
          • LEFT JOIN
          • RIGHT OUTER JOIN
          • RIGHT JOIN
          • FULL OUTER JOIN
          • FULL JOIN
          • OFFSET
          • LIMIT
          • WHERE
          Supported functions:
          • AVG()
          • SUM()
          • COUNT()
          • MIN()
          • MAX()
          • REDACTION()
          + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1GetQueryResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/query", + method="POST", + json={ + "query": query, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1GetQueryResponse, + parse_obj_as( + type_=V1GetQueryResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/records/__init__.py b/skyflow/generated/rest/records/__init__.py index b144d479..19c344fa 100644 --- a/skyflow/generated/rest/records/__init__.py +++ b/skyflow/generated/rest/records/__init__.py @@ -1,5 +1,7 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .types import ( RecordServiceBulkGetRecordRequestOrderBy, RecordServiceBulkGetRecordRequestRedaction, diff --git a/skyflow/generated/rest/records/client.py b/skyflow/generated/rest/records/client.py index d73e0da0..643e2826 100644 --- a/skyflow/generated/rest/records/client.py +++ b/skyflow/generated/rest/records/client.py @@ -1,30 +1,25 @@ # This file was auto-generated by Fern from our API Definition. import typing -from ..core.client_wrapper import SyncClientWrapper -from ..types.v_1_batch_record import V1BatchRecord -from ..types.v_1_byot import V1Byot + +from .. import core +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.request_options import RequestOptions from ..types.v_1_batch_operation_response import V1BatchOperationResponse -from ..core.jsonable_encoder import jsonable_encoder -from ..core.serialization import convert_and_respect_annotation_metadata -from ..core.pydantic_utilities import parse_obj_as -from ..errors.not_found_error import NotFoundError -from json.decoder import JSONDecodeError -from ..core.api_error import ApiError -from .types.record_service_bulk_get_record_request_redaction import RecordServiceBulkGetRecordRequestRedaction -from .types.record_service_bulk_get_record_request_order_by import RecordServiceBulkGetRecordRequestOrderBy +from ..types.v_1_batch_record import V1BatchRecord +from ..types.v_1_bulk_delete_record_response import V1BulkDeleteRecordResponse from ..types.v_1_bulk_get_record_response import V1BulkGetRecordResponse +from ..types.v_1_byot import V1Byot +from ..types.v_1_delete_file_response import V1DeleteFileResponse +from ..types.v_1_delete_record_response import V1DeleteRecordResponse from ..types.v_1_field_records import V1FieldRecords +from ..types.v_1_get_file_scan_status_response import V1GetFileScanStatusResponse from ..types.v_1_insert_record_response import V1InsertRecordResponse -from ..types.v_1_bulk_delete_record_response import V1BulkDeleteRecordResponse -from .types.record_service_get_record_request_redaction import RecordServiceGetRecordRequestRedaction from ..types.v_1_update_record_response import V1UpdateRecordResponse -from ..types.v_1_delete_record_response import V1DeleteRecordResponse -from .. import core -from ..types.v_1_delete_file_response import V1DeleteFileResponse -from ..types.v_1_get_file_scan_status_response import V1GetFileScanStatusResponse -from ..core.client_wrapper import AsyncClientWrapper +from .raw_client import AsyncRawRecordsClient, RawRecordsClient +from .types.record_service_bulk_get_record_request_order_by import RecordServiceBulkGetRecordRequestOrderBy +from .types.record_service_bulk_get_record_request_redaction import RecordServiceBulkGetRecordRequestRedaction +from .types.record_service_get_record_request_redaction import RecordServiceGetRecordRequestRedaction # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -32,7 +27,18 @@ class RecordsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = RawRecordsClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawRecordsClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawRecordsClient + """ + return self._raw_client def record_service_batch_operation( self, @@ -69,80 +75,19 @@ def record_service_batch_operation( Examples -------- - from skyflow import Skyflow, V1BatchRecord - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.record_service_batch_operation( - vault_id="vaultID", - records=[ - V1BatchRecord( - fields={ - "drivers_license_number": "89867453", - "name": "Connor", - "phone_number": "8794523160", - "ssn": "143-89-2306", - }, - table_name="persons", - method="POST", - batch_id="persons-12345", - redaction="PLAIN_TEXT", - tokenization=False, - download_url=False, - upsert="drivers_license_number", - ), - V1BatchRecord( - table_name="persons", - method="GET", - batch_id="persons-12345", - redaction="PLAIN_TEXT", - tokenization=False, - id="f1dbc55c-7c9b-495d-9a36-72bb2b619202", - download_url=True, - ), - ], - ) + from skyflow import Skyflow + from skyflow import V1BatchRecord + client = Skyflow(token="YOUR_TOKEN", ) + client.records.record_service_batch_operation(vault_id='vaultID', records=[V1BatchRecord(fields={'drivers_license_number': '89867453' + , 'name': 'Connor' + , 'phone_number': '8794523160' + , 'ssn': '143-89-2306' + }, table_name='persons', method="POST", batch_id='persons-12345', redaction="PLAIN_TEXT", tokenization=False, download_url=False, upsert='drivers_license_number', ), V1BatchRecord(table_name='persons', method="GET", batch_id='persons-12345', redaction="PLAIN_TEXT", tokenization=False, id='f1dbc55c-7c9b-495d-9a36-72bb2b619202', download_url=True, )], ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}", - method="POST", - json={ - "records": convert_and_respect_annotation_metadata( - object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write" - ), - "continueOnError": continue_on_error, - "byot": byot, - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, + _response = self._raw_client.record_service_batch_operation( + vault_id, records=records, continue_on_error=continue_on_error, byot=byot, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BatchOperationResponse, - parse_obj_as( - type_=V1BatchOperationResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def record_service_bulk_get_record( self, @@ -213,55 +158,25 @@ def record_service_bulk_get_record( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.record_service_bulk_get_record( - vault_id="vaultID", - object_name="objectName", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.records.record_service_bulk_get_record(vault_id='vaultID', object_name='objectName', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", - method="GET", - params={ - "skyflow_ids": skyflow_ids, - "redaction": redaction, - "tokenization": tokenization, - "fields": fields, - "offset": offset, - "limit": limit, - "downloadURL": download_url, - "column_name": column_name, - "column_values": column_values, - "order_by": order_by, - }, + _response = self._raw_client.record_service_bulk_get_record( + vault_id, + object_name, + skyflow_ids=skyflow_ids, + redaction=redaction, + tokenization=tokenization, + fields=fields, + offset=offset, + limit=limit, + download_url=download_url, + column_name=column_name, + column_values=column_values, + order_by=order_by, request_options=request_options, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BulkGetRecordResponse, - parse_obj_as( - type_=V1BulkGetRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def record_service_insert_record( self, @@ -310,78 +225,30 @@ def record_service_insert_record( Examples -------- - from skyflow import Skyflow, V1FieldRecords - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.record_service_insert_record( - vault_id="vaultID", - object_name="objectName", - records=[ - V1FieldRecords( - fields={ - "drivers_license_number": "13456789", - "name": "John", - "phone_number": "1236784563", - "ssn": "123-45-6789", - }, - ), - V1FieldRecords( - fields={ - "drivers_license_number": "98765432", - "name": "James", - "phone_number": "9876543215", - "ssn": "345-45-9876", - }, - ), - ], - tokenization=True, - upsert="drivers_license_number", - homogeneous=False, - ) + from skyflow import Skyflow + from skyflow import V1FieldRecords + client = Skyflow(token="YOUR_TOKEN", ) + client.records.record_service_insert_record(vault_id='vaultID', object_name='objectName', records=[V1FieldRecords(fields={'drivers_license_number': '13456789' + , 'name': 'John' + , 'phone_number': '1236784563' + , 'ssn': '123-45-6789' + }, ), V1FieldRecords(fields={'drivers_license_number': '98765432' + , 'name': 'James' + , 'phone_number': '9876543215' + , 'ssn': '345-45-9876' + }, )], tokenization=True, upsert='drivers_license_number', homogeneous=False, ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", - method="POST", - json={ - "records": convert_and_respect_annotation_metadata( - object_=records, annotation=typing.Sequence[V1FieldRecords], direction="write" - ), - "tokenization": tokenization, - "upsert": upsert, - "homogeneous": homogeneous, - "byot": byot, - }, - headers={ - "content-type": "application/json", - }, + _response = self._raw_client.record_service_insert_record( + vault_id, + object_name, + records=records, + tokenization=tokenization, + upsert=upsert, + homogeneous=homogeneous, + byot=byot, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1InsertRecordResponse, - parse_obj_as( - type_=V1InsertRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def record_service_bulk_delete_record( self, @@ -416,54 +283,13 @@ def record_service_bulk_delete_record( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.record_service_bulk_delete_record( - vault_id="vaultID", - object_name="objectName", - skyflow_ids=[ - "51782ea4-91a5-4430-a06d-f4b76efd3d2f", - "110ce08f-6059-4874-b1ae-7c6651d286ff", - ], - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.records.record_service_bulk_delete_record(vault_id='vaultID', object_name='objectName', skyflow_ids=['51782ea4-91a5-4430-a06d-f4b76efd3d2f', '110ce08f-6059-4874-b1ae-7c6651d286ff'], ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", - method="DELETE", - json={ - "skyflow_ids": skyflow_ids, - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, + _response = self._raw_client.record_service_bulk_delete_record( + vault_id, object_name, skyflow_ids=skyflow_ids, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BulkDeleteRecordResponse, - parse_obj_as( - type_=V1BulkDeleteRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def record_service_get_record( self, @@ -514,50 +340,20 @@ def record_service_get_record( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.record_service_get_record( - vault_id="vaultID", - object_name="objectName", - id="ID", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.records.record_service_get_record(vault_id='vaultID', object_name='objectName', id='ID', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", - method="GET", - params={ - "redaction": redaction, - "tokenization": tokenization, - "fields": fields, - "downloadURL": download_url, - }, + _response = self._raw_client.record_service_get_record( + vault_id, + object_name, + id, + redaction=redaction, + tokenization=tokenization, + fields=fields, + download_url=download_url, request_options=request_options, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1FieldRecords, - parse_obj_as( - type_=V1FieldRecords, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def record_service_update_record( self, @@ -601,65 +397,25 @@ def record_service_update_record( Examples -------- - from skyflow import Skyflow, V1FieldRecords - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.record_service_update_record( - vault_id="vaultID", - object_name="objectName", - id="ID", - record=V1FieldRecords( - fields={ - "drivers_license_number": "89867453", - "name": "Steve Smith", - "phone_number": "8794523160", - "ssn": "143-89-2306", - }, - ), - tokenization=True, - ) + from skyflow import Skyflow + from skyflow import V1FieldRecords + client = Skyflow(token="YOUR_TOKEN", ) + client.records.record_service_update_record(vault_id='vaultID', object_name='objectName', id='ID', record=V1FieldRecords(fields={'drivers_license_number': '89867453' + , 'name': 'Steve Smith' + , 'phone_number': '8794523160' + , 'ssn': '143-89-2306' + }, ), tokenization=True, ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", - method="PUT", - json={ - "record": convert_and_respect_annotation_metadata( - object_=record, annotation=V1FieldRecords, direction="write" - ), - "tokenization": tokenization, - "byot": byot, - }, - headers={ - "content-type": "application/json", - }, + _response = self._raw_client.record_service_update_record( + vault_id, + object_name, + id, + record=record, + tokenization=tokenization, + byot=byot, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1UpdateRecordResponse, - parse_obj_as( - type_=V1UpdateRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def record_service_delete_record( self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None @@ -689,44 +445,13 @@ def record_service_delete_record( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.record_service_delete_record( - vault_id="vaultID", - object_name="objectName", - id="ID", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.records.record_service_delete_record(vault_id='vaultID', object_name='objectName', id='ID', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", - method="DELETE", - request_options=request_options, + _response = self._raw_client.record_service_delete_record( + vault_id, object_name, id, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1DeleteRecordResponse, - parse_obj_as( - type_=V1DeleteRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def file_service_upload_file( self, @@ -765,49 +490,13 @@ def file_service_upload_file( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.file_service_upload_file( - vault_id="vaultID", - object_name="objectName", - id="ID", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.records.file_service_upload_file(vault_id='vaultID', object_name='objectName', id='ID', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}/files", - method="POST", - data={}, - files={ - "fileColumnName": file_column_name, - }, - request_options=request_options, - omit=OMIT, + _response = self._raw_client.file_service_upload_file( + vault_id, object_name, id, file_column_name=file_column_name, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1UpdateRecordResponse, - parse_obj_as( - type_=V1UpdateRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def file_service_delete_file( self, @@ -846,45 +535,13 @@ def file_service_delete_file( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.file_service_delete_file( - vault_id="vaultID", - table_name="tableName", - id="ID", - column_name="columnName", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.records.file_service_delete_file(vault_id='vaultID', table_name='tableName', id='ID', column_name='columnName', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}", - method="DELETE", - request_options=request_options, + _response = self._raw_client.file_service_delete_file( + vault_id, table_name, id, column_name, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1DeleteFileResponse, - parse_obj_as( - type_=V1DeleteFileResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def file_service_get_file_scan_status( self, @@ -923,50 +580,29 @@ def file_service_get_file_scan_status( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.records.file_service_get_file_scan_status( - vault_id="vaultID", - table_name="tableName", - id="ID", - column_name="columnName", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.records.file_service_get_file_scan_status(vault_id='vaultID', table_name='tableName', id='ID', column_name='columnName', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}/scan-status", - method="GET", - request_options=request_options, + _response = self._raw_client.file_service_get_file_scan_status( + vault_id, table_name, id, column_name, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1GetFileScanStatusResponse, - parse_obj_as( - type_=V1GetFileScanStatusResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data class AsyncRecordsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = AsyncRawRecordsClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawRecordsClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawRecordsClient + """ + return self._raw_client async def record_service_batch_operation( self, @@ -1003,88 +639,22 @@ async def record_service_batch_operation( Examples -------- + from skyflow import AsyncSkyflow + from skyflow import V1BatchRecord import asyncio - - from skyflow import AsyncSkyflow, V1BatchRecord - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.record_service_batch_operation( - vault_id="vaultID", - records=[ - V1BatchRecord( - fields={ - "drivers_license_number": "89867453", - "name": "Connor", - "phone_number": "8794523160", - "ssn": "143-89-2306", - }, - table_name="persons", - method="POST", - batch_id="persons-12345", - redaction="PLAIN_TEXT", - tokenization=False, - download_url=False, - upsert="drivers_license_number", - ), - V1BatchRecord( - table_name="persons", - method="GET", - batch_id="persons-12345", - redaction="PLAIN_TEXT", - tokenization=False, - id="f1dbc55c-7c9b-495d-9a36-72bb2b619202", - download_url=True, - ), - ], - ) - - + await client.records.record_service_batch_operation(vault_id='vaultID', records=[V1BatchRecord(fields={'drivers_license_number': '89867453' + , 'name': 'Connor' + , 'phone_number': '8794523160' + , 'ssn': '143-89-2306' + }, table_name='persons', method="POST", batch_id='persons-12345', redaction="PLAIN_TEXT", tokenization=False, download_url=False, upsert='drivers_license_number', ), V1BatchRecord(table_name='persons', method="GET", batch_id='persons-12345', redaction="PLAIN_TEXT", tokenization=False, id='f1dbc55c-7c9b-495d-9a36-72bb2b619202', download_url=True, )], ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}", - method="POST", - json={ - "records": convert_and_respect_annotation_metadata( - object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write" - ), - "continueOnError": continue_on_error, - "byot": byot, - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, + _response = await self._raw_client.record_service_batch_operation( + vault_id, records=records, continue_on_error=continue_on_error, byot=byot, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BatchOperationResponse, - parse_obj_as( - type_=V1BatchOperationResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def record_service_bulk_get_record( self, @@ -1154,64 +724,29 @@ async def record_service_bulk_get_record( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.record_service_bulk_get_record( - vault_id="vaultID", - object_name="objectName", - ) - - + await client.records.record_service_bulk_get_record(vault_id='vaultID', object_name='objectName', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", - method="GET", - params={ - "skyflow_ids": skyflow_ids, - "redaction": redaction, - "tokenization": tokenization, - "fields": fields, - "offset": offset, - "limit": limit, - "downloadURL": download_url, - "column_name": column_name, - "column_values": column_values, - "order_by": order_by, - }, + _response = await self._raw_client.record_service_bulk_get_record( + vault_id, + object_name, + skyflow_ids=skyflow_ids, + redaction=redaction, + tokenization=tokenization, + fields=fields, + offset=offset, + limit=limit, + download_url=download_url, + column_name=column_name, + column_values=column_values, + order_by=order_by, request_options=request_options, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BulkGetRecordResponse, - parse_obj_as( - type_=V1BulkGetRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def record_service_insert_record( self, @@ -1260,86 +795,33 @@ async def record_service_insert_record( Examples -------- + from skyflow import AsyncSkyflow + from skyflow import V1FieldRecords import asyncio - - from skyflow import AsyncSkyflow, V1FieldRecords - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.record_service_insert_record( - vault_id="vaultID", - object_name="objectName", - records=[ - V1FieldRecords( - fields={ - "drivers_license_number": "13456789", - "name": "John", - "phone_number": "1236784563", - "ssn": "123-45-6789", - }, - ), - V1FieldRecords( - fields={ - "drivers_license_number": "98765432", - "name": "James", - "phone_number": "9876543215", - "ssn": "345-45-9876", - }, - ), - ], - tokenization=True, - upsert="drivers_license_number", - homogeneous=False, - ) - - + await client.records.record_service_insert_record(vault_id='vaultID', object_name='objectName', records=[V1FieldRecords(fields={'drivers_license_number': '13456789' + , 'name': 'John' + , 'phone_number': '1236784563' + , 'ssn': '123-45-6789' + }, ), V1FieldRecords(fields={'drivers_license_number': '98765432' + , 'name': 'James' + , 'phone_number': '9876543215' + , 'ssn': '345-45-9876' + }, )], tokenization=True, upsert='drivers_license_number', homogeneous=False, ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", - method="POST", - json={ - "records": convert_and_respect_annotation_metadata( - object_=records, annotation=typing.Sequence[V1FieldRecords], direction="write" - ), - "tokenization": tokenization, - "upsert": upsert, - "homogeneous": homogeneous, - "byot": byot, - }, - headers={ - "content-type": "application/json", - }, + _response = await self._raw_client.record_service_insert_record( + vault_id, + object_name, + records=records, + tokenization=tokenization, + upsert=upsert, + homogeneous=homogeneous, + byot=byot, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1InsertRecordResponse, - parse_obj_as( - type_=V1InsertRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def record_service_bulk_delete_record( self, @@ -1373,63 +855,17 @@ async def record_service_bulk_delete_record( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.record_service_bulk_delete_record( - vault_id="vaultID", - object_name="objectName", - skyflow_ids=[ - "51782ea4-91a5-4430-a06d-f4b76efd3d2f", - "110ce08f-6059-4874-b1ae-7c6651d286ff", - ], - ) - - + await client.records.record_service_bulk_delete_record(vault_id='vaultID', object_name='objectName', skyflow_ids=['51782ea4-91a5-4430-a06d-f4b76efd3d2f', '110ce08f-6059-4874-b1ae-7c6651d286ff'], ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", - method="DELETE", - json={ - "skyflow_ids": skyflow_ids, - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, + _response = await self._raw_client.record_service_bulk_delete_record( + vault_id, object_name, skyflow_ids=skyflow_ids, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1BulkDeleteRecordResponse, - parse_obj_as( - type_=V1BulkDeleteRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def record_service_get_record( self, @@ -1479,59 +915,24 @@ async def record_service_get_record( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.record_service_get_record( - vault_id="vaultID", - object_name="objectName", - id="ID", - ) - - + await client.records.record_service_get_record(vault_id='vaultID', object_name='objectName', id='ID', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", - method="GET", - params={ - "redaction": redaction, - "tokenization": tokenization, - "fields": fields, - "downloadURL": download_url, - }, + _response = await self._raw_client.record_service_get_record( + vault_id, + object_name, + id, + redaction=redaction, + tokenization=tokenization, + fields=fields, + download_url=download_url, request_options=request_options, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1FieldRecords, - parse_obj_as( - type_=V1FieldRecords, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def record_service_update_record( self, @@ -1575,73 +976,28 @@ async def record_service_update_record( Examples -------- + from skyflow import AsyncSkyflow + from skyflow import V1FieldRecords import asyncio - - from skyflow import AsyncSkyflow, V1FieldRecords - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.record_service_update_record( - vault_id="vaultID", - object_name="objectName", - id="ID", - record=V1FieldRecords( - fields={ - "drivers_license_number": "89867453", - "name": "Steve Smith", - "phone_number": "8794523160", - "ssn": "143-89-2306", - }, - ), - tokenization=True, - ) - - + await client.records.record_service_update_record(vault_id='vaultID', object_name='objectName', id='ID', record=V1FieldRecords(fields={'drivers_license_number': '89867453' + , 'name': 'Steve Smith' + , 'phone_number': '8794523160' + , 'ssn': '143-89-2306' + }, ), tokenization=True, ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", - method="PUT", - json={ - "record": convert_and_respect_annotation_metadata( - object_=record, annotation=V1FieldRecords, direction="write" - ), - "tokenization": tokenization, - "byot": byot, - }, - headers={ - "content-type": "application/json", - }, + _response = await self._raw_client.record_service_update_record( + vault_id, + object_name, + id, + record=record, + tokenization=tokenization, + byot=byot, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1UpdateRecordResponse, - parse_obj_as( - type_=V1UpdateRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def record_service_delete_record( self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None @@ -1670,53 +1026,17 @@ async def record_service_delete_record( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.record_service_delete_record( - vault_id="vaultID", - object_name="objectName", - id="ID", - ) - - + await client.records.record_service_delete_record(vault_id='vaultID', object_name='objectName', id='ID', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", - method="DELETE", - request_options=request_options, + _response = await self._raw_client.record_service_delete_record( + vault_id, object_name, id, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1DeleteRecordResponse, - parse_obj_as( - type_=V1DeleteRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def file_service_upload_file( self, @@ -1754,58 +1074,17 @@ async def file_service_upload_file( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.file_service_upload_file( - vault_id="vaultID", - object_name="objectName", - id="ID", - ) - - + await client.records.file_service_upload_file(vault_id='vaultID', object_name='objectName', id='ID', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}/files", - method="POST", - data={}, - files={ - "fileColumnName": file_column_name, - }, - request_options=request_options, - omit=OMIT, + _response = await self._raw_client.file_service_upload_file( + vault_id, object_name, id, file_column_name=file_column_name, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1UpdateRecordResponse, - parse_obj_as( - type_=V1UpdateRecordResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def file_service_delete_file( self, @@ -1843,54 +1122,17 @@ async def file_service_delete_file( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.file_service_delete_file( - vault_id="vaultID", - table_name="tableName", - id="ID", - column_name="columnName", - ) - - + await client.records.file_service_delete_file(vault_id='vaultID', table_name='tableName', id='ID', column_name='columnName', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}", - method="DELETE", - request_options=request_options, + _response = await self._raw_client.file_service_delete_file( + vault_id, table_name, id, column_name, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1DeleteFileResponse, - parse_obj_as( - type_=V1DeleteFileResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def file_service_get_file_scan_status( self, @@ -1928,51 +1170,14 @@ async def file_service_get_file_scan_status( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.records.file_service_get_file_scan_status( - vault_id="vaultID", - table_name="tableName", - id="ID", - column_name="columnName", - ) - - + await client.records.file_service_get_file_scan_status(vault_id='vaultID', table_name='tableName', id='ID', column_name='columnName', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}/scan-status", - method="GET", - request_options=request_options, + _response = await self._raw_client.file_service_get_file_scan_status( + vault_id, table_name, id, column_name, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1GetFileScanStatusResponse, - parse_obj_as( - type_=V1GetFileScanStatusResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data diff --git a/skyflow/generated/rest/records/raw_client.py b/skyflow/generated/rest/records/raw_client.py new file mode 100644 index 00000000..3bbed594 --- /dev/null +++ b/skyflow/generated/rest/records/raw_client.py @@ -0,0 +1,1545 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from .. import core +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..core.serialization import convert_and_respect_annotation_metadata +from ..errors.not_found_error import NotFoundError +from ..types.v_1_batch_operation_response import V1BatchOperationResponse +from ..types.v_1_batch_record import V1BatchRecord +from ..types.v_1_bulk_delete_record_response import V1BulkDeleteRecordResponse +from ..types.v_1_bulk_get_record_response import V1BulkGetRecordResponse +from ..types.v_1_byot import V1Byot +from ..types.v_1_delete_file_response import V1DeleteFileResponse +from ..types.v_1_delete_record_response import V1DeleteRecordResponse +from ..types.v_1_field_records import V1FieldRecords +from ..types.v_1_get_file_scan_status_response import V1GetFileScanStatusResponse +from ..types.v_1_insert_record_response import V1InsertRecordResponse +from ..types.v_1_update_record_response import V1UpdateRecordResponse +from .types.record_service_bulk_get_record_request_order_by import RecordServiceBulkGetRecordRequestOrderBy +from .types.record_service_bulk_get_record_request_redaction import RecordServiceBulkGetRecordRequestRedaction +from .types.record_service_get_record_request_redaction import RecordServiceGetRecordRequestRedaction + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawRecordsClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def record_service_batch_operation( + self, + vault_id: str, + *, + records: typing.Optional[typing.Sequence[V1BatchRecord]] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1BatchOperationResponse]: + """ + Performs multiple record operations in a single transaction. + + Parameters + ---------- + vault_id : str + ID of the vault. + + records : typing.Optional[typing.Sequence[V1BatchRecord]] + Record operations to perform. + + continue_on_error : typing.Optional[bool] + Continue performing operations on partial errors. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1BatchOperationResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write" + ), + "continueOnError": continue_on_error, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BatchOperationResponse, + parse_obj_as( + type_=V1BatchOperationResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def record_service_bulk_get_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + redaction: typing.Optional[RecordServiceBulkGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + offset: typing.Optional[str] = None, + limit: typing.Optional[str] = None, + download_url: typing.Optional[bool] = None, + column_name: typing.Optional[str] = None, + column_values: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + order_by: typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1BulkGetRecordResponse]: + """ + Gets the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table that contains the records. + + skyflow_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]] + `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

          If not specified, returns the first 25 records in the table. + + redaction : typing.Optional[RecordServiceBulkGetRecordRequestRedaction] + Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + offset : typing.Optional[str] + Record position at which to start receiving data. + + limit : typing.Optional[str] + Number of record to return. Maximum 25. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + column_name : typing.Optional[str] + Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + column_values : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

          `column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + order_by : typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] + Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1BulkGetRecordResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="GET", + params={ + "skyflow_ids": skyflow_ids, + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "offset": offset, + "limit": limit, + "downloadURL": download_url, + "column_name": column_name, + "column_values": column_values, + "order_by": order_by, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BulkGetRecordResponse, + parse_obj_as( + type_=V1BulkGetRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def record_service_insert_record( + self, + vault_id: str, + object_name: str, + *, + records: typing.Optional[typing.Sequence[V1FieldRecords]] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + upsert: typing.Optional[str] = OMIT, + homogeneous: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1InsertRecordResponse]: + """ + Inserts a record in the specified table.

          The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.

          Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + records : typing.Optional[typing.Sequence[V1FieldRecords]] + Record values and tokens. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + upsert : typing.Optional[str] + Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.

          When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. + + homogeneous : typing.Optional[bool] + If `true`, this operation mandates that all the records have the same fields. This parameter does not work with upsert. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1InsertRecordResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1FieldRecords], direction="write" + ), + "tokenization": tokenization, + "upsert": upsert, + "homogeneous": homogeneous, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1InsertRecordResponse, + parse_obj_as( + type_=V1InsertRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def record_service_bulk_delete_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Sequence[str]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1BulkDeleteRecordResponse]: + """ + Deletes the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + skyflow_ids : typing.Optional[typing.Sequence[str]] + `skyflow_id` values of the records to delete. If `*` is specified, this operation deletes all records in the table. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1BulkDeleteRecordResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="DELETE", + json={ + "skyflow_ids": skyflow_ids, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BulkDeleteRecordResponse, + parse_obj_as( + type_=V1BulkDeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def record_service_get_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + redaction: typing.Optional[RecordServiceGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + download_url: typing.Optional[bool] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1FieldRecords]: + """ + Returns the specified record from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + redaction : typing.Optional[RecordServiceGetRecordRequestRedaction] + Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1FieldRecords] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="GET", + params={ + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "downloadURL": download_url, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1FieldRecords, + parse_obj_as( + type_=V1FieldRecords, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def record_service_update_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + record: typing.Optional[V1FieldRecords] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1UpdateRecordResponse]: + """ + Updates the specified record in a table.

          When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

          The time-to-live (TTL) for a transient field resets when the field value is updated. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + record : typing.Optional[V1FieldRecords] + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1UpdateRecordResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="PUT", + json={ + "record": convert_and_respect_annotation_metadata( + object_=record, annotation=V1FieldRecords, direction="write" + ), + "tokenization": tokenization, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def record_service_delete_record( + self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[V1DeleteRecordResponse]: + """ + Deletes the specified record from a table.

          Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record to delete. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1DeleteRecordResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1DeleteRecordResponse, + parse_obj_as( + type_=V1DeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def file_service_upload_file( + self, + vault_id: str, + object_name: str, + id: str, + *, + file_column_name: typing.Optional[core.File] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1UpdateRecordResponse]: + """ + Uploads a file to the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + file_column_name : typing.Optional[core.File] + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1UpdateRecordResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}/files", + method="POST", + data={}, + files={ + **({"fileColumnName": file_column_name} if fileColumnName is not None else {}), + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def file_service_delete_file( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1DeleteFileResponse]: + """ + Deletes a file from the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1DeleteFileResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1DeleteFileResponse, + parse_obj_as( + type_=V1DeleteFileResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def file_service_get_file_scan_status( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1GetFileScanStatusResponse]: + """ + Returns the anti-virus scan status of a file. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1GetFileScanStatusResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}/scan-status", + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1GetFileScanStatusResponse, + parse_obj_as( + type_=V1GetFileScanStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + +class AsyncRawRecordsClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def record_service_batch_operation( + self, + vault_id: str, + *, + records: typing.Optional[typing.Sequence[V1BatchRecord]] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1BatchOperationResponse]: + """ + Performs multiple record operations in a single transaction. + + Parameters + ---------- + vault_id : str + ID of the vault. + + records : typing.Optional[typing.Sequence[V1BatchRecord]] + Record operations to perform. + + continue_on_error : typing.Optional[bool] + Continue performing operations on partial errors. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1BatchOperationResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write" + ), + "continueOnError": continue_on_error, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BatchOperationResponse, + parse_obj_as( + type_=V1BatchOperationResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def record_service_bulk_get_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + redaction: typing.Optional[RecordServiceBulkGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + offset: typing.Optional[str] = None, + limit: typing.Optional[str] = None, + download_url: typing.Optional[bool] = None, + column_name: typing.Optional[str] = None, + column_values: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + order_by: typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1BulkGetRecordResponse]: + """ + Gets the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table that contains the records. + + skyflow_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]] + `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.

          If not specified, returns the first 25 records in the table. + + redaction : typing.Optional[RecordServiceBulkGetRecordRequestRedaction] + Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + offset : typing.Optional[str] + Record position at which to start receiving data. + + limit : typing.Optional[str] + Number of record to return. Maximum 25. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + column_name : typing.Optional[str] + Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + column_values : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.

          `column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. + + order_by : typing.Optional[RecordServiceBulkGetRecordRequestOrderBy] + Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1BulkGetRecordResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="GET", + params={ + "skyflow_ids": skyflow_ids, + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "offset": offset, + "limit": limit, + "downloadURL": download_url, + "column_name": column_name, + "column_values": column_values, + "order_by": order_by, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BulkGetRecordResponse, + parse_obj_as( + type_=V1BulkGetRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def record_service_insert_record( + self, + vault_id: str, + object_name: str, + *, + records: typing.Optional[typing.Sequence[V1FieldRecords]] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + upsert: typing.Optional[str] = OMIT, + homogeneous: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1InsertRecordResponse]: + """ + Inserts a record in the specified table.

          The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.

          Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + records : typing.Optional[typing.Sequence[V1FieldRecords]] + Record values and tokens. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + upsert : typing.Optional[str] + Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.

          When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. + + homogeneous : typing.Optional[bool] + If `true`, this operation mandates that all the records have the same fields. This parameter does not work with upsert. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1InsertRecordResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="POST", + json={ + "records": convert_and_respect_annotation_metadata( + object_=records, annotation=typing.Sequence[V1FieldRecords], direction="write" + ), + "tokenization": tokenization, + "upsert": upsert, + "homogeneous": homogeneous, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1InsertRecordResponse, + parse_obj_as( + type_=V1InsertRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def record_service_bulk_delete_record( + self, + vault_id: str, + object_name: str, + *, + skyflow_ids: typing.Optional[typing.Sequence[str]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1BulkDeleteRecordResponse]: + """ + Deletes the specified records from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + skyflow_ids : typing.Optional[typing.Sequence[str]] + `skyflow_id` values of the records to delete. If `*` is specified, this operation deletes all records in the table. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1BulkDeleteRecordResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}", + method="DELETE", + json={ + "skyflow_ids": skyflow_ids, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1BulkDeleteRecordResponse, + parse_obj_as( + type_=V1BulkDeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def record_service_get_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + redaction: typing.Optional[RecordServiceGetRecordRequestRedaction] = None, + tokenization: typing.Optional[bool] = None, + fields: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + download_url: typing.Optional[bool] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1FieldRecords]: + """ + Returns the specified record from a table. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + redaction : typing.Optional[RecordServiceGetRecordRequestRedaction] + Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + + fields : typing.Optional[typing.Union[str, typing.Sequence[str]]] + Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.

          If not specified, returns all fields. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1FieldRecords] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="GET", + params={ + "redaction": redaction, + "tokenization": tokenization, + "fields": fields, + "downloadURL": download_url, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1FieldRecords, + parse_obj_as( + type_=V1FieldRecords, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def record_service_update_record( + self, + vault_id: str, + object_name: str, + id: str, + *, + record: typing.Optional[V1FieldRecords] = OMIT, + tokenization: typing.Optional[bool] = OMIT, + byot: typing.Optional[V1Byot] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1UpdateRecordResponse]: + """ + Updates the specified record in a table.

          When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

          The time-to-live (TTL) for a transient field resets when the field value is updated. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + record : typing.Optional[V1FieldRecords] + + tokenization : typing.Optional[bool] + If `true`, this operation returns tokens for fields with tokenization enabled. + + byot : typing.Optional[V1Byot] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1UpdateRecordResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="PUT", + json={ + "record": convert_and_respect_annotation_metadata( + object_=record, annotation=V1FieldRecords, direction="write" + ), + "tokenization": tokenization, + "byot": byot, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def record_service_delete_record( + self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[V1DeleteRecordResponse]: + """ + Deletes the specified record from a table.

          Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record to delete. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1DeleteRecordResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1DeleteRecordResponse, + parse_obj_as( + type_=V1DeleteRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def file_service_upload_file( + self, + vault_id: str, + object_name: str, + id: str, + *, + file_column_name: typing.Optional[core.File] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1UpdateRecordResponse]: + """ + Uploads a file to the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + object_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + file_column_name : typing.Optional[core.File] + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1UpdateRecordResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(object_name)}/{jsonable_encoder(id)}/files", + method="POST", + data={}, + files={ + **({"fileColumnName": file_column_name} if fileColumnName is not None else {}), + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1UpdateRecordResponse, + parse_obj_as( + type_=V1UpdateRecordResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def file_service_delete_file( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1DeleteFileResponse]: + """ + Deletes a file from the specified record. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1DeleteFileResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}", + method="DELETE", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1DeleteFileResponse, + parse_obj_as( + type_=V1DeleteFileResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def file_service_get_file_scan_status( + self, + vault_id: str, + table_name: str, + id: str, + column_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1GetFileScanStatusResponse]: + """ + Returns the anti-virus scan status of a file. + + Parameters + ---------- + vault_id : str + ID of the vault. + + table_name : str + Name of the table. + + id : str + `skyflow_id` of the record. + + column_name : str + Name of the column that contains the file. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1GetFileScanStatusResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/{jsonable_encoder(table_name)}/{jsonable_encoder(id)}/files/{jsonable_encoder(column_name)}/scan-status", + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1GetFileScanStatusResponse, + parse_obj_as( + type_=V1GetFileScanStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/records/types/__init__.py b/skyflow/generated/rest/records/types/__init__.py index 9e9ce24e..62f7c5c2 100644 --- a/skyflow/generated/rest/records/types/__init__.py +++ b/skyflow/generated/rest/records/types/__init__.py @@ -1,5 +1,7 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .record_service_bulk_get_record_request_order_by import RecordServiceBulkGetRecordRequestOrderBy from .record_service_bulk_get_record_request_redaction import RecordServiceBulkGetRecordRequestRedaction from .record_service_get_record_request_redaction import RecordServiceGetRecordRequestRedaction diff --git a/skyflow/generated/rest/tokens/__init__.py b/skyflow/generated/rest/tokens/__init__.py index f3ea2659..5cde0202 100644 --- a/skyflow/generated/rest/tokens/__init__.py +++ b/skyflow/generated/rest/tokens/__init__.py @@ -1,2 +1,4 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + diff --git a/skyflow/generated/rest/tokens/client.py b/skyflow/generated/rest/tokens/client.py index 641050fe..d7861277 100644 --- a/skyflow/generated/rest/tokens/client.py +++ b/skyflow/generated/rest/tokens/client.py @@ -1,19 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from ..core.client_wrapper import SyncClientWrapper -from ..types.v_1_detokenize_record_request import V1DetokenizeRecordRequest + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.request_options import RequestOptions +from ..types.v_1_detokenize_record_request import V1DetokenizeRecordRequest from ..types.v_1_detokenize_response import V1DetokenizeResponse -from ..core.jsonable_encoder import jsonable_encoder -from ..core.serialization import convert_and_respect_annotation_metadata -from ..core.pydantic_utilities import parse_obj_as -from ..errors.not_found_error import NotFoundError -from json.decoder import JSONDecodeError -from ..core.api_error import ApiError from ..types.v_1_tokenize_record_request import V1TokenizeRecordRequest from ..types.v_1_tokenize_response import V1TokenizeResponse -from ..core.client_wrapper import AsyncClientWrapper +from .raw_client import AsyncRawTokensClient, RawTokensClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +16,18 @@ class TokensClient: def __init__(self, *, client_wrapper: SyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = RawTokensClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawTokensClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawTokensClient + """ + return self._raw_client def record_service_detokenize( self, @@ -59,67 +65,19 @@ def record_service_detokenize( Examples -------- - from skyflow import Skyflow, V1DetokenizeRecordRequest - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.tokens.record_service_detokenize( - vault_id="vaultID", - detokenization_parameters=[ - V1DetokenizeRecordRequest( - token="afbd1074-51c1-4a16-9eee-e2c0ecb52125", - redaction="PLAIN_TEXT", - ), - V1DetokenizeRecordRequest( - token="05383487-fcae-42e5-a48e-5bd62a51af12", - redaction="DEFAULT", - ), - ], - download_url=False, - ) + from skyflow import Skyflow + from skyflow import V1DetokenizeRecordRequest + client = Skyflow(token="YOUR_TOKEN", ) + client.tokens.record_service_detokenize(vault_id='vaultID', detokenization_parameters=[V1DetokenizeRecordRequest(token='afbd1074-51c1-4a16-9eee-e2c0ecb52125', redaction="PLAIN_TEXT", ), V1DetokenizeRecordRequest(token='05383487-fcae-42e5-a48e-5bd62a51af12', redaction="DEFAULT", )], download_url=False, ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/detokenize", - method="POST", - json={ - "detokenizationParameters": convert_and_respect_annotation_metadata( - object_=detokenization_parameters, - annotation=typing.Sequence[V1DetokenizeRecordRequest], - direction="write", - ), - "downloadURL": download_url, - "continueOnError": continue_on_error, - }, - headers={ - "content-type": "application/json", - }, + _response = self._raw_client.record_service_detokenize( + vault_id, + detokenization_parameters=detokenization_parameters, + download_url=download_url, + continue_on_error=continue_on_error, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1DetokenizeResponse, - parse_obj_as( - type_=V1DetokenizeResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data def record_service_tokenize( self, @@ -150,58 +108,29 @@ def record_service_tokenize( Examples -------- from skyflow import Skyflow - - client = Skyflow( - token="YOUR_TOKEN", - ) - client.tokens.record_service_tokenize( - vault_id="vaultID", - ) + client = Skyflow(token="YOUR_TOKEN", ) + client.tokens.record_service_tokenize(vault_id='vaultID', ) """ - _response = self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/tokenize", - method="POST", - json={ - "tokenizationParameters": convert_and_respect_annotation_metadata( - object_=tokenization_parameters, - annotation=typing.Sequence[V1TokenizeRecordRequest], - direction="write", - ), - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, + _response = self._raw_client.record_service_tokenize( + vault_id, tokenization_parameters=tokenization_parameters, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1TokenizeResponse, - parse_obj_as( - type_=V1TokenizeResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data class AsyncTokensClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): - self._client_wrapper = client_wrapper + self._raw_client = AsyncRawTokensClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawTokensClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawTokensClient + """ + return self._raw_client async def record_service_detokenize( self, @@ -239,75 +168,22 @@ async def record_service_detokenize( Examples -------- + from skyflow import AsyncSkyflow + from skyflow import V1DetokenizeRecordRequest import asyncio - - from skyflow import AsyncSkyflow, V1DetokenizeRecordRequest - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.tokens.record_service_detokenize( - vault_id="vaultID", - detokenization_parameters=[ - V1DetokenizeRecordRequest( - token="afbd1074-51c1-4a16-9eee-e2c0ecb52125", - redaction="PLAIN_TEXT", - ), - V1DetokenizeRecordRequest( - token="05383487-fcae-42e5-a48e-5bd62a51af12", - redaction="DEFAULT", - ), - ], - download_url=False, - ) - - + await client.tokens.record_service_detokenize(vault_id='vaultID', detokenization_parameters=[V1DetokenizeRecordRequest(token='afbd1074-51c1-4a16-9eee-e2c0ecb52125', redaction="PLAIN_TEXT", ), V1DetokenizeRecordRequest(token='05383487-fcae-42e5-a48e-5bd62a51af12', redaction="DEFAULT", )], download_url=False, ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/detokenize", - method="POST", - json={ - "detokenizationParameters": convert_and_respect_annotation_metadata( - object_=detokenization_parameters, - annotation=typing.Sequence[V1DetokenizeRecordRequest], - direction="write", - ), - "downloadURL": download_url, - "continueOnError": continue_on_error, - }, - headers={ - "content-type": "application/json", - }, + _response = await self._raw_client.record_service_detokenize( + vault_id, + detokenization_parameters=detokenization_parameters, + download_url=download_url, + continue_on_error=continue_on_error, request_options=request_options, - omit=OMIT, ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1DetokenizeResponse, - parse_obj_as( - type_=V1DetokenizeResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data async def record_service_tokenize( self, @@ -337,59 +213,14 @@ async def record_service_tokenize( Examples -------- - import asyncio - from skyflow import AsyncSkyflow - - client = AsyncSkyflow( - token="YOUR_TOKEN", - ) - - + import asyncio + client = AsyncSkyflow(token="YOUR_TOKEN", ) async def main() -> None: - await client.tokens.record_service_tokenize( - vault_id="vaultID", - ) - - + await client.tokens.record_service_tokenize(vault_id='vaultID', ) asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request( - f"v1/vaults/{jsonable_encoder(vault_id)}/tokenize", - method="POST", - json={ - "tokenizationParameters": convert_and_respect_annotation_metadata( - object_=tokenization_parameters, - annotation=typing.Sequence[V1TokenizeRecordRequest], - direction="write", - ), - }, - headers={ - "content-type": "application/json", - }, - request_options=request_options, - omit=OMIT, + _response = await self._raw_client.record_service_tokenize( + vault_id, tokenization_parameters=tokenization_parameters, request_options=request_options ) - try: - if 200 <= _response.status_code < 300: - return typing.cast( - V1TokenizeResponse, - parse_obj_as( - type_=V1TokenizeResponse, # type: ignore - object_=_response.json(), - ), - ) - if _response.status_code == 404: - raise NotFoundError( - typing.cast( - typing.Dict[str, typing.Optional[typing.Any]], - parse_obj_as( - type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore - object_=_response.json(), - ), - ) - ) - _response_json = _response.json() - except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + return _response.data diff --git a/skyflow/generated/rest/tokens/raw_client.py b/skyflow/generated/rest/tokens/raw_client.py new file mode 100644 index 00000000..58dfa94d --- /dev/null +++ b/skyflow/generated/rest/tokens/raw_client.py @@ -0,0 +1,318 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..core.serialization import convert_and_respect_annotation_metadata +from ..errors.not_found_error import NotFoundError +from ..types.v_1_detokenize_record_request import V1DetokenizeRecordRequest +from ..types.v_1_detokenize_response import V1DetokenizeResponse +from ..types.v_1_tokenize_record_request import V1TokenizeRecordRequest +from ..types.v_1_tokenize_response import V1TokenizeResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawTokensClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def record_service_detokenize( + self, + vault_id: str, + *, + detokenization_parameters: typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] = OMIT, + download_url: typing.Optional[bool] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1DetokenizeResponse]: + """ + Returns records that correspond to the specified tokens. + + Parameters + ---------- + vault_id : str + ID of the vault. + + detokenization_parameters : typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] + Detokenization details. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + continue_on_error : typing.Optional[bool] + If `true`, the detokenization request continues even if an error occurs. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1DetokenizeResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/detokenize", + method="POST", + json={ + "detokenizationParameters": convert_and_respect_annotation_metadata( + object_=detokenization_parameters, + annotation=typing.Sequence[V1DetokenizeRecordRequest], + direction="write", + ), + "downloadURL": download_url, + "continueOnError": continue_on_error, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1DetokenizeResponse, + parse_obj_as( + type_=V1DetokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + def record_service_tokenize( + self, + vault_id: str, + *, + tokenization_parameters: typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[V1TokenizeResponse]: + """ + Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.

          Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see Insert Record and the tokenization parameter. + + Parameters + ---------- + vault_id : str + ID of the vault. + + tokenization_parameters : typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] + Tokenization details. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[V1TokenizeResponse] + A successful response. + """ + _response = self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/tokenize", + method="POST", + json={ + "tokenizationParameters": convert_and_respect_annotation_metadata( + object_=tokenization_parameters, + annotation=typing.Sequence[V1TokenizeRecordRequest], + direction="write", + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1TokenizeResponse, + parse_obj_as( + type_=V1TokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + +class AsyncRawTokensClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def record_service_detokenize( + self, + vault_id: str, + *, + detokenization_parameters: typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] = OMIT, + download_url: typing.Optional[bool] = OMIT, + continue_on_error: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1DetokenizeResponse]: + """ + Returns records that correspond to the specified tokens. + + Parameters + ---------- + vault_id : str + ID of the vault. + + detokenization_parameters : typing.Optional[typing.Sequence[V1DetokenizeRecordRequest]] + Detokenization details. + + download_url : typing.Optional[bool] + If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + + continue_on_error : typing.Optional[bool] + If `true`, the detokenization request continues even if an error occurs. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1DetokenizeResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/detokenize", + method="POST", + json={ + "detokenizationParameters": convert_and_respect_annotation_metadata( + object_=detokenization_parameters, + annotation=typing.Sequence[V1DetokenizeRecordRequest], + direction="write", + ), + "downloadURL": download_url, + "continueOnError": continue_on_error, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1DetokenizeResponse, + parse_obj_as( + type_=V1DetokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + + async def record_service_tokenize( + self, + vault_id: str, + *, + tokenization_parameters: typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[V1TokenizeResponse]: + """ + Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.

          Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see Insert Record and the tokenization parameter. + + Parameters + ---------- + vault_id : str + ID of the vault. + + tokenization_parameters : typing.Optional[typing.Sequence[V1TokenizeRecordRequest]] + Tokenization details. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[V1TokenizeResponse] + A successful response. + """ + _response = await self._client_wrapper.httpx_client.request( + f"v1/vaults/{jsonable_encoder(vault_id)}/tokenize", + method="POST", + json={ + "tokenizationParameters": convert_and_respect_annotation_metadata( + object_=tokenization_parameters, + annotation=typing.Sequence[V1TokenizeRecordRequest], + direction="write", + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + V1TokenizeResponse, + parse_obj_as( + type_=V1TokenizeResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 404: + raise NotFoundError( + typing.cast( + typing.Dict[str, typing.Optional[typing.Any]], + parse_obj_as( + type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore + object_=_response.json(), + ), + ) + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) + raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) diff --git a/skyflow/generated/rest/types/__init__.py b/skyflow/generated/rest/types/__init__.py index d2112008..093756ee 100644 --- a/skyflow/generated/rest/types/__init__.py +++ b/skyflow/generated/rest/types/__init__.py @@ -1,5 +1,7 @@ # This file was auto-generated by Fern from our API Definition. +# isort: skip_file + from .audit_event_audit_resource_type import AuditEventAuditResourceType from .audit_event_context import AuditEventContext from .audit_event_data import AuditEventData diff --git a/skyflow/generated/rest/types/audit_event_context.py b/skyflow/generated/rest/types/audit_event_context.py index 178137ec..92287d5a 100644 --- a/skyflow/generated/rest/types/audit_event_context.py +++ b/skyflow/generated/rest/types/audit_event_context.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel -import typing_extensions import typing -from ..core.serialization import FieldMetadata + import pydantic -from .v_1_member_type import V1MemberType +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.serialization import FieldMetadata from .context_access_type import ContextAccessType from .context_auth_mode import ContextAuthMode -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from .v_1_member_type import V1MemberType class AuditEventContext(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/audit_event_data.py b/skyflow/generated/rest/types/audit_event_data.py index 78385d17..9449de24 100644 --- a/skyflow/generated/rest/types/audit_event_data.py +++ b/skyflow/generated/rest/types/audit_event_data.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class AuditEventData(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/audit_event_http_info.py b/skyflow/generated/rest/types/audit_event_http_info.py index 14df874b..093119e3 100644 --- a/skyflow/generated/rest/types/audit_event_http_info.py +++ b/skyflow/generated/rest/types/audit_event_http_info.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel -import typing_extensions import typing -from ..core.serialization import FieldMetadata + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.serialization import FieldMetadata class AuditEventHttpInfo(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/googlerpc_status.py b/skyflow/generated/rest/types/googlerpc_status.py index aceede7e..f0a885b4 100644 --- a/skyflow/generated/rest/types/googlerpc_status.py +++ b/skyflow/generated/rest/types/googlerpc_status.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .protobuf_any import ProtobufAny -from ..core.pydantic_utilities import IS_PYDANTIC_V2 + import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .protobuf_any import ProtobufAny class GooglerpcStatus(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/protobuf_any.py b/skyflow/generated/rest/types/protobuf_any.py index 9d141254..9062870c 100644 --- a/skyflow/generated/rest/types/protobuf_any.py +++ b/skyflow/generated/rest/types/protobuf_any.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel -import typing_extensions import typing -from ..core.serialization import FieldMetadata -from ..core.pydantic_utilities import IS_PYDANTIC_V2 + import pydantic +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.serialization import FieldMetadata class ProtobufAny(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_audit_after_options.py b/skyflow/generated/rest/types/v_1_audit_after_options.py index 0f078667..6d10157e 100644 --- a/skyflow/generated/rest/types/v_1_audit_after_options.py +++ b/skyflow/generated/rest/types/v_1_audit_after_options.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..core.serialization import FieldMetadata -from ..core.pydantic_utilities import IS_PYDANTIC_V2 class V1AuditAfterOptions(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_audit_event_response.py b/skyflow/generated/rest/types/v_1_audit_event_response.py index 2ff30533..d82e8999 100644 --- a/skyflow/generated/rest/types/v_1_audit_event_response.py +++ b/skyflow/generated/rest/types/v_1_audit_event_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .audit_event_data import AuditEventData -from ..core.pydantic_utilities import IS_PYDANTIC_V2 class V1AuditEventResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_audit_response.py b/skyflow/generated/rest/types/v_1_audit_response.py index 617c1fd9..fe0b358a 100644 --- a/skyflow/generated/rest/types/v_1_audit_response.py +++ b/skyflow/generated/rest/types/v_1_audit_response.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_audit_response_event import V1AuditResponseEvent + import pydantic import typing_extensions -from .v_1_audit_after_options import V1AuditAfterOptions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..core.serialization import FieldMetadata -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from .v_1_audit_after_options import V1AuditAfterOptions +from .v_1_audit_response_event import V1AuditResponseEvent class V1AuditResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_audit_response_event.py b/skyflow/generated/rest/types/v_1_audit_response_event.py index b623257e..dbea54a2 100644 --- a/skyflow/generated/rest/types/v_1_audit_response_event.py +++ b/skyflow/generated/rest/types/v_1_audit_response_event.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .audit_event_context import AuditEventContext -from .v_1_audit_response_event_request import V1AuditResponseEventRequest -from .v_1_audit_event_response import V1AuditEventResponse + +import pydantic import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..core.serialization import FieldMetadata -import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from .audit_event_context import AuditEventContext +from .v_1_audit_event_response import V1AuditEventResponse +from .v_1_audit_response_event_request import V1AuditResponseEventRequest class V1AuditResponseEvent(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_audit_response_event_request.py b/skyflow/generated/rest/types/v_1_audit_response_event_request.py index 5eb9a709..6127818d 100644 --- a/skyflow/generated/rest/types/v_1_audit_response_event_request.py +++ b/skyflow/generated/rest/types/v_1_audit_response_event_request.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .audit_event_data import AuditEventData + +import pydantic import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..core.serialization import FieldMetadata -import pydantic -from .request_action_type import RequestActionType from .audit_event_audit_resource_type import AuditEventAuditResourceType +from .audit_event_data import AuditEventData from .audit_event_http_info import AuditEventHttpInfo -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from .request_action_type import RequestActionType class V1AuditResponseEventRequest(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_batch_operation_response.py b/skyflow/generated/rest/types/v_1_batch_operation_response.py index 72643ce2..9e7144a6 100644 --- a/skyflow/generated/rest/types/v_1_batch_operation_response.py +++ b/skyflow/generated/rest/types/v_1_batch_operation_response.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel -import typing_extensions import typing -from ..core.serialization import FieldMetadata + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.serialization import FieldMetadata class V1BatchOperationResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_batch_record.py b/skyflow/generated/rest/types/v_1_batch_record.py index 7dca5fda..d531fc5e 100644 --- a/skyflow/generated/rest/types/v_1_batch_record.py +++ b/skyflow/generated/rest/types/v_1_batch_record.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..core.serialization import FieldMetadata from .batch_record_method import BatchRecordMethod from .redaction_enum_redaction import RedactionEnumRedaction -from ..core.pydantic_utilities import IS_PYDANTIC_V2 class V1BatchRecord(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_bin_list_response.py b/skyflow/generated/rest/types/v_1_bin_list_response.py index bd4f69b9..24d7fad7 100644 --- a/skyflow/generated/rest/types/v_1_bin_list_response.py +++ b/skyflow/generated/rest/types/v_1_bin_list_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_card import V1Card + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .v_1_card import V1Card class V1BinListResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_bulk_delete_record_response.py b/skyflow/generated/rest/types/v_1_bulk_delete_record_response.py index 6d03bccd..bae86dc3 100644 --- a/skyflow/generated/rest/types/v_1_bulk_delete_record_response.py +++ b/skyflow/generated/rest/types/v_1_bulk_delete_record_response.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel -import typing_extensions import typing -from ..core.serialization import FieldMetadata + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.serialization import FieldMetadata class V1BulkDeleteRecordResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_bulk_get_record_response.py b/skyflow/generated/rest/types/v_1_bulk_get_record_response.py index 7244bc7f..385a8132 100644 --- a/skyflow/generated/rest/types/v_1_bulk_get_record_response.py +++ b/skyflow/generated/rest/types/v_1_bulk_get_record_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_field_records import V1FieldRecords + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .v_1_field_records import V1FieldRecords class V1BulkGetRecordResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_card.py b/skyflow/generated/rest/types/v_1_card.py index c5a641b1..1c862169 100644 --- a/skyflow/generated/rest/types/v_1_card.py +++ b/skyflow/generated/rest/types/v_1_card.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel -import typing_extensions import typing -from ..core.serialization import FieldMetadata + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.serialization import FieldMetadata class V1Card(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_delete_file_response.py b/skyflow/generated/rest/types/v_1_delete_file_response.py index 6e995cec..927517e9 100644 --- a/skyflow/generated/rest/types/v_1_delete_file_response.py +++ b/skyflow/generated/rest/types/v_1_delete_file_response.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class V1DeleteFileResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_delete_record_response.py b/skyflow/generated/rest/types/v_1_delete_record_response.py index 366cb30b..4007abca 100644 --- a/skyflow/generated/rest/types/v_1_delete_record_response.py +++ b/skyflow/generated/rest/types/v_1_delete_record_response.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class V1DeleteRecordResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_detokenize_record_request.py b/skyflow/generated/rest/types/v_1_detokenize_record_request.py index b6e225c3..ef75d346 100644 --- a/skyflow/generated/rest/types/v_1_detokenize_record_request.py +++ b/skyflow/generated/rest/types/v_1_detokenize_record_request.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .redaction_enum_redaction import RedactionEnumRedaction -from ..core.pydantic_utilities import IS_PYDANTIC_V2 class V1DetokenizeRecordRequest(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_detokenize_record_response.py b/skyflow/generated/rest/types/v_1_detokenize_record_response.py index bbc26aa0..4cce821c 100644 --- a/skyflow/generated/rest/types/v_1_detokenize_record_response.py +++ b/skyflow/generated/rest/types/v_1_detokenize_record_response.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic import typing_extensions -from .detokenize_record_response_value_type import DetokenizeRecordResponseValueType +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..core.serialization import FieldMetadata -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from .detokenize_record_response_value_type import DetokenizeRecordResponseValueType class V1DetokenizeRecordResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_detokenize_response.py b/skyflow/generated/rest/types/v_1_detokenize_response.py index 63e97c84..34759550 100644 --- a/skyflow/generated/rest/types/v_1_detokenize_response.py +++ b/skyflow/generated/rest/types/v_1_detokenize_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_detokenize_record_response import V1DetokenizeRecordResponse + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .v_1_detokenize_record_response import V1DetokenizeRecordResponse class V1DetokenizeResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_field_records.py b/skyflow/generated/rest/types/v_1_field_records.py index 07a8bf58..fbedfcfe 100644 --- a/skyflow/generated/rest/types/v_1_field_records.py +++ b/skyflow/generated/rest/types/v_1_field_records.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class V1FieldRecords(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_get_auth_token_response.py b/skyflow/generated/rest/types/v_1_get_auth_token_response.py index d414ed7c..c4db65a0 100644 --- a/skyflow/generated/rest/types/v_1_get_auth_token_response.py +++ b/skyflow/generated/rest/types/v_1_get_auth_token_response.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel -import typing_extensions import typing -from ..core.serialization import FieldMetadata + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.serialization import FieldMetadata class V1GetAuthTokenResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_get_file_scan_status_response.py b/skyflow/generated/rest/types/v_1_get_file_scan_status_response.py index 71349961..70801b56 100644 --- a/skyflow/generated/rest/types/v_1_get_file_scan_status_response.py +++ b/skyflow/generated/rest/types/v_1_get_file_scan_status_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_file_av_scan_status import V1FileAvScanStatus -from ..core.pydantic_utilities import IS_PYDANTIC_V2 + import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .v_1_file_av_scan_status import V1FileAvScanStatus class V1GetFileScanStatusResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_get_query_response.py b/skyflow/generated/rest/types/v_1_get_query_response.py index 778a517a..0edf0513 100644 --- a/skyflow/generated/rest/types/v_1_get_query_response.py +++ b/skyflow/generated/rest/types/v_1_get_query_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_field_records import V1FieldRecords + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .v_1_field_records import V1FieldRecords class V1GetQueryResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_insert_record_response.py b/skyflow/generated/rest/types/v_1_insert_record_response.py index a3344c92..d303a2f9 100644 --- a/skyflow/generated/rest/types/v_1_insert_record_response.py +++ b/skyflow/generated/rest/types/v_1_insert_record_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_record_meta_properties import V1RecordMetaProperties + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .v_1_record_meta_properties import V1RecordMetaProperties class V1InsertRecordResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_record_meta_properties.py b/skyflow/generated/rest/types/v_1_record_meta_properties.py index a4eb95b7..bc51f5c5 100644 --- a/skyflow/generated/rest/types/v_1_record_meta_properties.py +++ b/skyflow/generated/rest/types/v_1_record_meta_properties.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class V1RecordMetaProperties(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_tokenize_record_request.py b/skyflow/generated/rest/types/v_1_tokenize_record_request.py index 9fba53a2..1801aeb7 100644 --- a/skyflow/generated/rest/types/v_1_tokenize_record_request.py +++ b/skyflow/generated/rest/types/v_1_tokenize_record_request.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..core.serialization import FieldMetadata -from ..core.pydantic_utilities import IS_PYDANTIC_V2 class V1TokenizeRecordRequest(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_tokenize_record_response.py b/skyflow/generated/rest/types/v_1_tokenize_record_response.py index c105e9fc..fd449283 100644 --- a/skyflow/generated/rest/types/v_1_tokenize_record_response.py +++ b/skyflow/generated/rest/types/v_1_tokenize_record_response.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class V1TokenizeRecordResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_tokenize_response.py b/skyflow/generated/rest/types/v_1_tokenize_response.py index 0e1886b4..f882cc24 100644 --- a/skyflow/generated/rest/types/v_1_tokenize_response.py +++ b/skyflow/generated/rest/types/v_1_tokenize_response.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing -from .v_1_tokenize_record_response import V1TokenizeRecordResponse + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .v_1_tokenize_record_response import V1TokenizeRecordResponse class V1TokenizeResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_update_record_response.py b/skyflow/generated/rest/types/v_1_update_record_response.py index be6da8fb..c17a3933 100644 --- a/skyflow/generated/rest/types/v_1_update_record_response.py +++ b/skyflow/generated/rest/types/v_1_update_record_response.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class V1UpdateRecordResponse(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_vault_field_mapping.py b/skyflow/generated/rest/types/v_1_vault_field_mapping.py index a567d639..c681b94d 100644 --- a/skyflow/generated/rest/types/v_1_vault_field_mapping.py +++ b/skyflow/generated/rest/types/v_1_vault_field_mapping.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel class V1VaultFieldMapping(UniversalBaseModel): diff --git a/skyflow/generated/rest/types/v_1_vault_schema_config.py b/skyflow/generated/rest/types/v_1_vault_schema_config.py index a3f3f0b6..b61e30ea 100644 --- a/skyflow/generated/rest/types/v_1_vault_schema_config.py +++ b/skyflow/generated/rest/types/v_1_vault_schema_config.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.pydantic_utilities import UniversalBaseModel import typing + import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .v_1_vault_field_mapping import V1VaultFieldMapping -from ..core.pydantic_utilities import IS_PYDANTIC_V2 class V1VaultSchemaConfig(UniversalBaseModel): diff --git a/skyflow/generated/rest/version.py b/skyflow/generated/rest/version.py index f8d02ff4..5a6bc65e 100644 --- a/skyflow/generated/rest/version.py +++ b/skyflow/generated/rest/version.py @@ -1 +1 @@ -__version__ = '2.0.0b1.dev0+3d4ee51' +__version__ = "2.0.0" \ No newline at end of file From 463ffc263c8fab4a85fb6ef7d16a57dfb9b04a48 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 2 May 2025 20:27:08 +0530 Subject: [PATCH 12/24] SK-1909 Handle API error cases after fern migration --- skyflow/utils/_utils.py | 30 +++++++++++++---- skyflow/vault/controller/_vault.py | 4 +-- tests/utils/test__utils.py | 22 ++++++------ tests/vault/controller/test__vault.py | 48 +++++++++++++++------------ 4 files changed, 63 insertions(+), 41 deletions(-) diff --git a/skyflow/utils/_utils.py b/skyflow/utils/_utils.py index 8f035e93..13556af1 100644 --- a/skyflow/utils/_utils.py +++ b/skyflow/utils/_utils.py @@ -13,6 +13,7 @@ from skyflow.error import SkyflowError from skyflow.generated.rest import V1UpdateRecordResponse, V1BulkDeleteRecordResponse, \ V1DetokenizeResponse, V1TokenizeResponse, V1GetQueryResponse, V1BulkGetRecordResponse +from skyflow.generated.rest.core.http_response import HttpResponse from skyflow.utils.logger import log_error_log from . import SkyflowMessages, SDK_VERSION from .constants import PROTOCOL @@ -192,11 +193,16 @@ def get_metrics(): def parse_insert_response(api_response, continue_on_error): + # Retrieve the headers and data from the API response + api_response_headers = api_response.headers + api_response_data = api_response.data + # Retrieve the request ID from the headers + request_id = api_response_headers.get('x-request-id') inserted_fields = [] errors = [] insert_response = InsertResponse() if continue_on_error: - for idx, response in enumerate(api_response.responses): + for idx, response in enumerate(api_response_data.responses): if response['Status'] == 200: body = response['Body'] if 'records' in body: @@ -212,6 +218,7 @@ def parse_insert_response(api_response, continue_on_error): elif response['Status'] == 400: error = { 'request_index': idx, + 'request_id': request_id, 'error': response['Body']['error'] } errors.append(error) @@ -220,7 +227,7 @@ def parse_insert_response(api_response, continue_on_error): insert_response.errors = errors else: - for record in api_response.records: + for record in api_response_data.records: field_data = { 'skyflow_id': record.skyflow_id } @@ -265,18 +272,24 @@ def parse_get_response(api_response: V1BulkGetRecordResponse): return get_response -def parse_detokenize_response(api_response: V1DetokenizeResponse): +def parse_detokenize_response(api_response: HttpResponse[V1DetokenizeResponse]): + # Retrieve the headers and data from the API response + api_response_headers = api_response.headers + api_response_data = api_response.data + # Retrieve the request ID from the headers + request_id = api_response_headers.get('x-request-id') detokenized_fields = [] errors = [] - for record in api_response.records: + for record in api_response_data.records: if record.error: errors.append({ "token": record.token, - "error": record.error + "error": record.error, + "request_id": request_id }) else: - value_type = record.value_type.value if record.value_type else None + value_type = record.value_type if record.value_type else None detokenized_fields.append({ "token": record.token, "value": record.value, @@ -372,7 +385,10 @@ def handle_exception(error, logger): def handle_json_error(err, data, request_id, logger): try: - description = json.loads(data) + if isinstance(data, dict): # If data is already a dict + description = data + else: + description = json.loads(data) status_code = description.get('error', {}).get('http_code', 500) # Default to 500 if not found http_status = description.get('error', {}).get('http_status') grpc_code = description.get('error', {}).get('grpc_code') diff --git a/skyflow/vault/controller/_vault.py b/skyflow/vault/controller/_vault.py index cabd82db..cef5ffa9 100644 --- a/skyflow/vault/controller/_vault.py +++ b/skyflow/vault/controller/_vault.py @@ -68,7 +68,7 @@ def insert(self, request: InsertRequest): validate_insert_request(self.__vault_client.get_logger(), request) log_info(SkyflowMessages.Info.INSERT_REQUEST_RESOLVED.value, self.__vault_client.get_logger()) self.__initialize() - records_api = self.__vault_client.get_records_api() + records_api = self.__vault_client.get_records_api().with_raw_response insert_body = self.__build_insert_body(request) try: @@ -196,7 +196,7 @@ def detokenize(self, request: DetokenizeRequest): ) for item in request.data ] - tokens_api = self.__vault_client.get_tokens_api() + tokens_api = self.__vault_client.get_tokens_api().with_raw_response try: log_info(SkyflowMessages.Info.DETOKENIZE_TRIGGERED.value, self.__vault_client.get_logger()) api_response = tokens_api.record_service_detokenize( diff --git a/tests/utils/test__utils.py b/tests/utils/test__utils.py index e70afc0e..a1254932 100644 --- a/tests/utils/test__utils.py +++ b/tests/utils/test__utils.py @@ -183,21 +183,22 @@ def test_construct_invoke_connection_request_with_form_date_content_type(self): def test_parse_insert_response(self): api_response = Mock() - api_response.responses = [ + api_response.headers = {"x-request-id": "12345", "content-type": "application/json"} + api_response.data = Mock(responses=[ {"Status": 200, "Body": {"records": [{"skyflow_id": "id1"}]}}, {"Status": 400, "Body": {"error": TEST_ERROR_MESSAGE}} - ] + ]) result = parse_insert_response(api_response, continue_on_error=True) self.assertEqual(len(result.inserted_fields), 1) self.assertEqual(len(result.errors), 1) def test_parse_insert_response_continue_on_error_false(self): mock_api_response = Mock() - mock_api_response.records = [ + mock_api_response.headers = {"x-request-id": "12345", "content-type": "application/json"} + mock_api_response.data = Mock(records=[ Mock(skyflow_id="id_1", tokens={"token1": "token_value1"}), Mock(skyflow_id="id_2", tokens={"token2": "token_value2"}) - ] - + ]) result = parse_insert_response(mock_api_response, continue_on_error=False) self.assertIsInstance(result, InsertResponse) @@ -252,11 +253,12 @@ def test_parse_get_response_successful(self): def test_parse_detokenize_response_with_mixed_records(self): mock_api_response = Mock() - mock_api_response.records = [ - Mock(token="token1", value="value1", value_type=Mock(value="Type1"), error=None), + mock_api_response.headers = {"x-request-id": "12345", "content-type": "application/json"} + mock_api_response.data = Mock(records=[ + Mock(token="token1", value="value1", value_type="Type1", error=None), Mock(token="token2", value=None, value_type=None, error="Some error"), - Mock(token="token3", value="value3", value_type=Mock(value="Type2"), error=None), - ] + Mock(token="token3", value="value3", value_type="Type2", error=None), + ]) result = parse_detokenize_response(mock_api_response) self.assertIsInstance(result, DetokenizeResponse) @@ -267,7 +269,7 @@ def test_parse_detokenize_response_with_mixed_records(self): ] expected_errors = [ - {"token": "token2", "error": "Some error"} + {"token": "token2", "error": "Some error", "request_id": "12345"} ] self.assertEqual(result.detokenized_fields, expected_detokenized_fields) diff --git a/tests/vault/controller/test__vault.py b/tests/vault/controller/test__vault.py index 89046e65..ea59189e 100644 --- a/tests/vault/controller/test__vault.py +++ b/tests/vault/controller/test__vault.py @@ -48,10 +48,12 @@ def test_insert_with_continue_on_error(self, mock_parse_response, mock_validate) # Mock API response to contain a mix of successful and failed insertions mock_api_response = Mock() - mock_api_response.responses = [ - {"Status": 200, "Body": {"records": [{"skyflow_id": "id1", "tokens": {"token_field": "token_val1"}}]}}, - {"Status": 400, "Body": {"error": "Insert error for record 2"}} - ] + mock_api_response.data = { + "responses":[ + {"Status": 200, "Body": {"records": [{"skyflow_id": "id1", "tokens": {"token_field": "token_val1"}}]}}, + {"Status": 400, "Body": {"error": "Insert error for record 2"}} + ] + } # Expected parsed response expected_inserted_fields = [ @@ -65,14 +67,14 @@ def test_insert_with_continue_on_error(self, mock_parse_response, mock_validate) # Set the return value for the parse response mock_parse_response.return_value = expected_response records_api = self.vault_client.get_records_api.return_value - records_api.record_service_batch_operation.return_value = mock_api_response + records_api.with_raw_response.record_service_batch_operation.return_value = mock_api_response # Call the insert function result = self.vault.insert(request) # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_batch_operation.assert_called_once_with( + records_api.with_raw_response.record_service_batch_operation.assert_called_once_with( VAULT_ID, records=expected_body, continue_on_error=True, @@ -107,8 +109,8 @@ def test_insert_with_continue_on_error_false(self, mock_parse_response, mock_val # Mock API response for a successful insert mock_api_response = Mock() - mock_api_response.records = [{"skyflow_id": "id1", "tokens": {"token_field": "token_val1"}}] - + mock_api_response.data = {"records":[{"skyflow_id": "id1", "tokens": {"token_field": "token_val1"}}]} + # Expected parsed response expected_inserted_fields = [{'skyflow_id': 'id1', 'token_field': 'token_val1'}] expected_response = InsertResponse(inserted_fields=expected_inserted_fields) @@ -116,14 +118,14 @@ def test_insert_with_continue_on_error_false(self, mock_parse_response, mock_val # Set the return value for the parse response mock_parse_response.return_value = expected_response records_api = self.vault_client.get_records_api.return_value - records_api.record_service_insert_record.return_value = mock_api_response + records_api.with_raw_response.record_service_insert_record.return_value = mock_api_response # Call the insert function result = self.vault.insert(request) # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_insert_record.assert_called_once_with( + records_api.with_raw_response.record_service_insert_record.assert_called_once_with( VAULT_ID, TABLE_NAME, records=expected_body, @@ -149,7 +151,7 @@ def test_insert_handles_generic_error(self, mock_validate): with self.assertRaises(Exception): self.vault.insert(request) - records_api.record_service_insert_record.assert_called_once() + records_api.with_raw_response.record_service_insert_record.assert_called_once() @patch("skyflow.vault.controller._vault.validate_insert_request") @patch("skyflow.vault.controller._vault.parse_insert_response") @@ -174,8 +176,8 @@ def test_insert_with_continue_on_error_false_when_tokens_are_not_none(self, mock # Mock API response for a successful insert mock_api_response = Mock() - mock_api_response.records = [{"skyflow_id": "id1", "tokens": {"token_field": "token_val1"}}] - + mock_api_response.data = {"records":[{"skyflow_id": "id1", "tokens": {"token_field": "token_val1"}}]} + # Expected parsed response expected_inserted_fields = [{'skyflow_id': 'id1', 'token_field': 'token_val1'}] expected_response = InsertResponse(inserted_fields=expected_inserted_fields) @@ -183,14 +185,14 @@ def test_insert_with_continue_on_error_false_when_tokens_are_not_none(self, mock # Set the return value for the parse response mock_parse_response.return_value = expected_response records_api = self.vault_client.get_records_api.return_value - records_api.record_service_insert_record.return_value = mock_api_response + records_api.with_raw_response.record_service_insert_record.return_value = mock_api_response # Call the insert function result = self.vault.insert(request) # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_insert_record.assert_called_once_with( + records_api.with_raw_response.record_service_insert_record.assert_called_once_with( VAULT_ID, TABLE_NAME, records=expected_body, @@ -528,10 +530,12 @@ def test_detokenize_successful(self, mock_parse_response, mock_validate): # Mock API response mock_api_response = Mock() - mock_api_response.records = [ - Mock(token="token1", value="value1", value_type=Mock(value="STRING"), error=None), - Mock(token="token2", value="value2", value_type=Mock(value="STRING"), error=None) - ] + mock_api_response.data = { + "records":[ + Mock(token="token1", value="value1", value_type=Mock(value="STRING"), error=None), + Mock(token="token2", value="value2", value_type=Mock(value="STRING"), error=None) + ] + } # Expected parsed response expected_fields = [ @@ -543,14 +547,14 @@ def test_detokenize_successful(self, mock_parse_response, mock_validate): # Set the return value for parse_detokenize_response mock_parse_response.return_value = expected_response tokens_api = self.vault_client.get_tokens_api.return_value - tokens_api.record_service_detokenize.return_value = mock_api_response + tokens_api.with_raw_response.record_service_detokenize.return_value = mock_api_response # Call the detokenize function result = self.vault.detokenize(request) # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - tokens_api.record_service_detokenize.assert_called_once_with( + tokens_api.with_raw_response.record_service_detokenize.assert_called_once_with( VAULT_ID, detokenization_parameters=expected_tokens_list, continue_on_error=False @@ -582,7 +586,7 @@ def test_detokenize_handles_generic_error(self, mock_validate): with self.assertRaises(Exception): self.vault.detokenize(request) - tokens_api.record_service_detokenize.assert_called_once() + tokens_api.with_raw_response.record_service_detokenize.assert_called_once() @patch("skyflow.vault.controller._vault.validate_tokenize_request") @patch("skyflow.vault.controller._vault.parse_tokenize_response") From f2ce4529143b344c4f28143ffa5b29589d4becf9 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 12 May 2025 11:57:57 +0530 Subject: [PATCH 13/24] SK-1909 Update fern generated code --- skyflow/generated/rest/audit/raw_client.py | 18 +- .../rest/authentication/raw_client.py | 38 ++-- .../generated/rest/bin_lookup/raw_client.py | 18 +- skyflow/generated/rest/core/client_wrapper.py | 2 +- .../rest/errors/bad_request_error.py | 8 +- .../generated/rest/errors/not_found_error.py | 8 +- .../rest/errors/unauthorized_error.py | 8 +- skyflow/generated/rest/query/raw_client.py | 18 +- skyflow/generated/rest/records/raw_client.py | 180 ++++++++++-------- skyflow/generated/rest/tokens/raw_client.py | 36 ++-- 10 files changed, 191 insertions(+), 143 deletions(-) diff --git a/skyflow/generated/rest/audit/raw_client.py b/skyflow/generated/rest/audit/raw_client.py index 9762e46d..b67b025e 100644 --- a/skyflow/generated/rest/audit/raw_client.py +++ b/skyflow/generated/rest/audit/raw_client.py @@ -242,18 +242,19 @@ def audit_service_list_audit_events( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) class AsyncRawAuditClient: @@ -468,15 +469,16 @@ async def audit_service_list_audit_events( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/skyflow/generated/rest/authentication/raw_client.py b/skyflow/generated/rest/authentication/raw_client.py index 0c2778c2..bb1c2ed7 100644 --- a/skyflow/generated/rest/authentication/raw_client.py +++ b/skyflow/generated/rest/authentication/raw_client.py @@ -92,38 +92,41 @@ def authentication_service_get_auth_token( return HttpResponse(response=_response, data=_data) if _response.status_code == 400: raise BadRequestError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) if _response.status_code == 401: raise UnauthorizedError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) class AsyncRawAuthenticationClient: @@ -201,35 +204,38 @@ async def authentication_service_get_auth_token( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 400: raise BadRequestError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) if _response.status_code == 401: raise UnauthorizedError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/skyflow/generated/rest/bin_lookup/raw_client.py b/skyflow/generated/rest/bin_lookup/raw_client.py index c021d684..90202931 100644 --- a/skyflow/generated/rest/bin_lookup/raw_client.py +++ b/skyflow/generated/rest/bin_lookup/raw_client.py @@ -83,18 +83,19 @@ def bin_list_service_list_cards_of_bin( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) class AsyncRawBinLookupClient: @@ -163,15 +164,16 @@ async def bin_list_service_list_cards_of_bin( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/skyflow/generated/rest/core/client_wrapper.py b/skyflow/generated/rest/core/client_wrapper.py index 2c55b8d9..b1396aef 100644 --- a/skyflow/generated/rest/core/client_wrapper.py +++ b/skyflow/generated/rest/core/client_wrapper.py @@ -22,7 +22,7 @@ def get_headers(self) -> typing.Dict[str, str]: headers: typing.Dict[str, str] = { "X-Fern-Language": "Python", "X-Fern-SDK-Name": "skyflow.generated.rest", - "X-Fern-SDK-Version": "0.0.163", + "X-Fern-SDK-Version": "0.0.166", } headers["Authorization"] = f"Bearer {self._get_token()}" return headers diff --git a/skyflow/generated/rest/errors/bad_request_error.py b/skyflow/generated/rest/errors/bad_request_error.py index 5f24fa6d..c5d0db48 100644 --- a/skyflow/generated/rest/errors/bad_request_error.py +++ b/skyflow/generated/rest/errors/bad_request_error.py @@ -6,5 +6,9 @@ class BadRequestError(ApiError): - def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): - super().__init__(status_code=400, body=body) + def __init__( + self, + body: typing.Dict[str, typing.Optional[typing.Any]], + headers: typing.Optional[typing.Dict[str, str]] = None, + ): + super().__init__(status_code=400, headers=headers, body=body) diff --git a/skyflow/generated/rest/errors/not_found_error.py b/skyflow/generated/rest/errors/not_found_error.py index 68977121..66307415 100644 --- a/skyflow/generated/rest/errors/not_found_error.py +++ b/skyflow/generated/rest/errors/not_found_error.py @@ -6,5 +6,9 @@ class NotFoundError(ApiError): - def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): - super().__init__(status_code=404, body=body) + def __init__( + self, + body: typing.Dict[str, typing.Optional[typing.Any]], + headers: typing.Optional[typing.Dict[str, str]] = None, + ): + super().__init__(status_code=404, headers=headers, body=body) diff --git a/skyflow/generated/rest/errors/unauthorized_error.py b/skyflow/generated/rest/errors/unauthorized_error.py index cd97f14d..3d58c2e6 100644 --- a/skyflow/generated/rest/errors/unauthorized_error.py +++ b/skyflow/generated/rest/errors/unauthorized_error.py @@ -6,5 +6,9 @@ class UnauthorizedError(ApiError): - def __init__(self, body: typing.Dict[str, typing.Optional[typing.Any]]): - super().__init__(status_code=401, body=body) + def __init__( + self, + body: typing.Dict[str, typing.Optional[typing.Any]], + headers: typing.Optional[typing.Dict[str, str]] = None, + ): + super().__init__(status_code=401, headers=headers, body=body) diff --git a/skyflow/generated/rest/query/raw_client.py b/skyflow/generated/rest/query/raw_client.py index b6a201a1..897d1e2d 100644 --- a/skyflow/generated/rest/query/raw_client.py +++ b/skyflow/generated/rest/query/raw_client.py @@ -70,18 +70,19 @@ def query_service_execute_query( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) class AsyncRawQueryClient: @@ -138,15 +139,16 @@ async def query_service_execute_query( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/skyflow/generated/rest/records/raw_client.py b/skyflow/generated/rest/records/raw_client.py index 3bbed594..55b874c6 100644 --- a/skyflow/generated/rest/records/raw_client.py +++ b/skyflow/generated/rest/records/raw_client.py @@ -96,18 +96,19 @@ def record_service_batch_operation( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def record_service_bulk_get_record( self, @@ -204,18 +205,19 @@ def record_service_bulk_get_record( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def record_service_insert_record( self, @@ -292,18 +294,19 @@ def record_service_insert_record( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def record_service_bulk_delete_record( self, @@ -359,18 +362,19 @@ def record_service_bulk_delete_record( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def record_service_get_record( self, @@ -441,18 +445,19 @@ def record_service_get_record( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def record_service_update_record( self, @@ -522,18 +527,19 @@ def record_service_update_record( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def record_service_delete_record( self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None @@ -577,18 +583,19 @@ def record_service_delete_record( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def file_service_upload_file( self, @@ -646,18 +653,19 @@ def file_service_upload_file( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def file_service_delete_file( self, @@ -710,18 +718,19 @@ def file_service_delete_file( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def file_service_get_file_scan_status( self, @@ -774,18 +783,19 @@ def file_service_get_file_scan_status( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) class AsyncRawRecordsClient: @@ -853,18 +863,19 @@ async def record_service_batch_operation( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def record_service_bulk_get_record( self, @@ -961,18 +972,19 @@ async def record_service_bulk_get_record( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def record_service_insert_record( self, @@ -1049,18 +1061,19 @@ async def record_service_insert_record( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def record_service_bulk_delete_record( self, @@ -1116,18 +1129,19 @@ async def record_service_bulk_delete_record( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def record_service_get_record( self, @@ -1198,18 +1212,19 @@ async def record_service_get_record( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def record_service_update_record( self, @@ -1279,18 +1294,19 @@ async def record_service_update_record( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def record_service_delete_record( self, vault_id: str, object_name: str, id: str, *, request_options: typing.Optional[RequestOptions] = None @@ -1334,18 +1350,19 @@ async def record_service_delete_record( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def file_service_upload_file( self, @@ -1403,18 +1420,19 @@ async def file_service_upload_file( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def file_service_delete_file( self, @@ -1467,18 +1485,19 @@ async def file_service_delete_file( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def file_service_get_file_scan_status( self, @@ -1531,15 +1550,16 @@ async def file_service_get_file_scan_status( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/skyflow/generated/rest/tokens/raw_client.py b/skyflow/generated/rest/tokens/raw_client.py index 58dfa94d..057b9f68 100644 --- a/skyflow/generated/rest/tokens/raw_client.py +++ b/skyflow/generated/rest/tokens/raw_client.py @@ -88,18 +88,19 @@ def record_service_detokenize( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) def record_service_tokenize( self, @@ -155,18 +156,19 @@ def record_service_tokenize( return HttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) class AsyncRawTokensClient: @@ -237,18 +239,19 @@ async def record_service_detokenize( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) async def record_service_tokenize( self, @@ -304,15 +307,16 @@ async def record_service_tokenize( return AsyncHttpResponse(response=_response, data=_data) if _response.status_code == 404: raise NotFoundError( - typing.cast( + headers=dict(_response.headers), + body=typing.cast( typing.Dict[str, typing.Optional[typing.Any]], parse_obj_as( type_=typing.Dict[str, typing.Optional[typing.Any]], # type: ignore object_=_response.json(), ), - ) + ), ) _response_json = _response.json() except JSONDecodeError: - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response.text) - raise ApiError(headers=dict(_response.headers), status_code=_response.status_code, body=_response_json) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) From a9a44d837b7d732c034838f81597d932290f3ad5 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 12 May 2025 14:28:59 +0530 Subject: [PATCH 14/24] SK-1909 Handle invalid cluster ID error scenario --- skyflow/utils/_skyflow_messages.py | 2 ++ skyflow/utils/_utils.py | 11 +++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/skyflow/utils/_skyflow_messages.py b/skyflow/utils/_skyflow_messages.py index e67c3f7f..4bc95354 100644 --- a/skyflow/utils/_skyflow_messages.py +++ b/skyflow/utils/_skyflow_messages.py @@ -16,6 +16,8 @@ class ErrorCodes(Enum): REDACTION_WITH_TOKENS_NOT_SUPPORTED = 400 class Error(Enum): + GENERIC_API_ERROR = f"{error_prefix} Validation error. Invalid configuration. Please add a valid vault configuration." + EMPTY_VAULT_ID = f"{error_prefix} Initialization failed. Invalid vault Id. Specify a valid vault Id." INVALID_VAULT_ID = f"{error_prefix} Initialization failed. Invalid vault Id. Specify a valid vault Id as a string." EMPTY_CLUSTER_ID = f"{error_prefix} Initialization failed. Invalid cluster Id for vault with id {{}}. Specify a valid cluster Id." diff --git a/skyflow/utils/_utils.py b/skyflow/utils/_utils.py index 13556af1..514ebf6d 100644 --- a/skyflow/utils/_utils.py +++ b/skyflow/utils/_utils.py @@ -3,6 +3,7 @@ import urllib.parse from dotenv import load_dotenv import dotenv +import httpx from requests.sessions import PreparedRequest from requests.models import HTTPError import requests @@ -369,6 +370,10 @@ def log_and_reject_error(description, status_code, request_id, http_status=None, raise SkyflowError(description, status_code, request_id, grpc_code, http_status, details) def handle_exception(error, logger): + # handle invalid cluster ID error scenario + if (isinstance(error, httpx.ConnectError)): + handle_generic_error(error, None, SkyflowMessages.ErrorCodes.INVALID_INPUT.value, logger) + request_id = error.headers.get('x-request-id', 'unknown-request-id') content_type = error.headers.get('content-type') data = error.body @@ -403,9 +408,11 @@ def handle_text_error(err, data, request_id, logger): log_and_reject_error(data, err.status, request_id, logger = logger) def handle_generic_error(err, request_id, logger): - description = "An error occurred." - log_and_reject_error(description, err.status, request_id, logger = logger) + handle_generic_error(err, request_id, err.status, logger = logger) +def handle_generic_error(err, request_id, status, logger): + description = SkyflowMessages.Error.GENERIC_API_ERROR.value + log_and_reject_error(description, status, request_id, logger = logger) def encode_column_values(get_request): encoded_column_values = list() From da88042a25aef2b18d56e2725c4003e6331681a8 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 14 May 2025 10:36:54 +0530 Subject: [PATCH 15/24] SK-1909 Fix inconsistencies and issues in Python SDK v2 --- skyflow/error/_skyflow_error.py | 2 +- skyflow/utils/_utils.py | 5 +++-- skyflow/vault/controller/_vault.py | 2 -- tests/vault/controller/test__connection.py | 2 +- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/skyflow/error/_skyflow_error.py b/skyflow/error/_skyflow_error.py index e23c0133..7b917fae 100644 --- a/skyflow/error/_skyflow_error.py +++ b/skyflow/error/_skyflow_error.py @@ -8,7 +8,7 @@ def __init__(self, request_id = None, grpc_code = None, http_status = None, - details = None): + details = []): self.message = message self.http_code = http_code self.grpc_code = grpc_code diff --git a/skyflow/utils/_utils.py b/skyflow/utils/_utils.py index 514ebf6d..f2822d06 100644 --- a/skyflow/utils/_utils.py +++ b/skyflow/utils/_utils.py @@ -359,7 +359,8 @@ def parse_invoke_connection_response(api_response: requests.Response): if error_from_client is not None: if details is None: details = [] - details.append({'error_from_client': error_from_client}) + error_from_client_bool = error_from_client.lower() == 'true' + details.append({'error_from_client': error_from_client_bool}) raise SkyflowError(message, status_code, request_id, grpc_code, http_status, details) except json.JSONDecodeError: @@ -397,7 +398,7 @@ def handle_json_error(err, data, request_id, logger): status_code = description.get('error', {}).get('http_code', 500) # Default to 500 if not found http_status = description.get('error', {}).get('http_status') grpc_code = description.get('error', {}).get('grpc_code') - details = description.get('error', {}).get('details') + details = description.get('error', {}).get('details', []) description_message = description.get('error', {}).get('message', "An unknown error occurred.") log_and_reject_error(description_message, status_code, request_id, http_status, grpc_code, details, logger = logger) diff --git a/skyflow/vault/controller/_vault.py b/skyflow/vault/controller/_vault.py index cef5ffa9..121890e9 100644 --- a/skyflow/vault/controller/_vault.py +++ b/skyflow/vault/controller/_vault.py @@ -43,8 +43,6 @@ def __build_batch_field_records(self, values, tokens, table_name, return_tokens, upsert=upsert, tokens=token ) - if token is not None: - batch_record.tokens = token batch_record_list.append(batch_record) return batch_record_list diff --git a/tests/vault/controller/test__connection.py b/tests/vault/controller/test__connection.py index 61be3163..adc73078 100644 --- a/tests/vault/controller/test__connection.py +++ b/tests/vault/controller/test__connection.py @@ -120,6 +120,6 @@ def test_parse_invoke_connection_response_error_from_client(self): exception = context.exception - self.assertTrue(any(detail.get('error_from_client') == 'true' for detail in exception.details)) + self.assertTrue(any(detail.get('error_from_client') == True for detail in exception.details)) self.assertEqual(exception.request_id, '12345') From d79488acaca7cf08bf196c580707289829daf059 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 14 May 2025 13:05:51 +0530 Subject: [PATCH 16/24] SK-1909 Fix issues in Python SDK v2 - Fix inconsistent response structure for invoke connection - Fix 404 Not found error for get by column values - Fix failing unit tests due to code changes --- skyflow/utils/_utils.py | 11 ++++------- .../vault/connection/_invoke_connection_response.py | 7 ++++--- skyflow/vault/controller/_vault.py | 2 -- tests/utils/test__utils.py | 4 ++-- tests/vault/controller/test__connection.py | 6 +++++- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/skyflow/utils/_utils.py b/skyflow/utils/_utils.py index f2822d06..4dbd32a3 100644 --- a/skyflow/utils/_utils.py +++ b/skyflow/utils/_utils.py @@ -326,8 +326,6 @@ def parse_query_response(api_response: V1GetQueryResponse): return query_response def parse_invoke_connection_response(api_response: requests.Response): - invoke_connection_response = InvokeConnectionResponse() - status_code = api_response.status_code content = api_response.content if isinstance(content, bytes): @@ -335,13 +333,12 @@ def parse_invoke_connection_response(api_response: requests.Response): try: api_response.raise_for_status() try: - json_content = json.loads(content) + data = json.loads(content) + metadata = {} if 'x-request-id' in api_response.headers: - request_id = api_response.headers['x-request-id'] - json_content['request_id'] = request_id + metadata['request_id'] = api_response.headers['x-request-id'] - invoke_connection_response.response = json_content - return invoke_connection_response + return InvokeConnectionResponse(data=data, metadata=metadata) except Exception as e: raise SkyflowError(SkyflowMessages.Error.RESPONSE_NOT_JSON.value.format(content), status_code) except HTTPError: diff --git a/skyflow/vault/connection/_invoke_connection_response.py b/skyflow/vault/connection/_invoke_connection_response.py index 661b61d3..818b94a1 100644 --- a/skyflow/vault/connection/_invoke_connection_response.py +++ b/skyflow/vault/connection/_invoke_connection_response.py @@ -1,9 +1,10 @@ class InvokeConnectionResponse: - def __init__(self, response = None): - self.response = response + def __init__(self, data=None, metadata=None): + self.data = data + self.metadata = metadata if metadata else {} def __repr__(self): - return f"ConnectionResponse({self.response})" + return f"ConnectionResponse('data'={self.data},'metadata'={self.metadata})" def __str__(self): return self.__repr__() \ No newline at end of file diff --git a/skyflow/vault/controller/_vault.py b/skyflow/vault/controller/_vault.py index 121890e9..c05d81f0 100644 --- a/skyflow/vault/controller/_vault.py +++ b/skyflow/vault/controller/_vault.py @@ -136,8 +136,6 @@ def delete(self, request: DeleteRequest): def get(self, request: GetRequest): log_info(SkyflowMessages.Info.VALIDATE_GET_REQUEST.value, self.__vault_client.get_logger()) validate_get_request(self.__vault_client.get_logger(), request) - if request.column_values: - request.column_values = encode_column_values(request) log_info(SkyflowMessages.Info.GET_REQUEST_RESOLVED.value, self.__vault_client.get_logger()) self.__initialize() records_api = self.__vault_client.get_records_api() diff --git a/tests/utils/test__utils.py b/tests/utils/test__utils.py index a1254932..a7306e7b 100644 --- a/tests/utils/test__utils.py +++ b/tests/utils/test__utils.py @@ -321,8 +321,8 @@ def test_parse_invoke_connection_response_successful(self, mock_response): result = parse_invoke_connection_response(mock_response) self.assertIsInstance(result, InvokeConnectionResponse) - self.assertEqual(result.response["key"], "value") - self.assertEqual(result.response["request_id"], "1234") + self.assertEqual(result.data["key"], "value") + self.assertEqual(result.metadata["request_id"], "1234") @patch("requests.Response") def test_parse_invoke_connection_response_json_decode_error(self, mock_response): diff --git a/tests/vault/controller/test__connection.py b/tests/vault/controller/test__connection.py index adc73078..70702514 100644 --- a/tests/vault/controller/test__connection.py +++ b/tests/vault/controller/test__connection.py @@ -53,7 +53,11 @@ def test_invoke_success(self, mock_send): response = self.connection.invoke(request) # Assertions for successful invocation - self.assertEqual(response.response, {"response": "success", "request_id": "test-request-id"}) + expected_response = { + 'data': {"response": "success"}, + 'metadata': {"request_id": "test-request-id"} + } + self.assertEqual(vars(response), expected_response) self.mock_vault_client.get_bearer_token.assert_called_once() @patch('requests.Session.send') From 385617f5bb5742d613d88d6256a3e21942d60ecb Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 14 May 2025 12:22:03 +0000 Subject: [PATCH 17/24] [AUTOMATED] Private Release 2.0.0b2.dev0+3a80017 --- setup.py | 2 +- skyflow/utils/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index fc1f9e6a..698c67fc 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ if sys.version_info < (3, 8): raise RuntimeError("skyflow requires Python 3.8+") -current_version = '2.0.0b2.dev0+f760bc0' +current_version = '2.0.0b2.dev0+3a80017' setup( name='skyflow', diff --git a/skyflow/utils/_version.py b/skyflow/utils/_version.py index d73d9196..a2802c11 100644 --- a/skyflow/utils/_version.py +++ b/skyflow/utils/_version.py @@ -1 +1 @@ -SDK_VERSION = '2.0.0b2.dev0+f760bc0' \ No newline at end of file +SDK_VERSION = '2.0.0b2.dev0+3a80017' \ No newline at end of file From b01869295c464042ff582f54e5cc90ca243f44be Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 14 May 2025 18:56:28 +0530 Subject: [PATCH 18/24] SK-1909 Update sample to trigger release --- samples/vault_api/client_operations.py | 1 - 1 file changed, 1 deletion(-) diff --git a/samples/vault_api/client_operations.py b/samples/vault_api/client_operations.py index 80a8ca3a..1f9f12ea 100644 --- a/samples/vault_api/client_operations.py +++ b/samples/vault_api/client_operations.py @@ -12,7 +12,6 @@ 3. Create a delete request 4. Handle response and errors """ - def perform_secure_data_deletion(): try: # Step 1: Configure Bearer Token Credentials From 3d817ab196c75e5c4fa32aca963b83ec02c5f94d Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 14 May 2025 18:59:11 +0530 Subject: [PATCH 19/24] SK-1909 Trigger internal release --- skyflow/vault/controller/_vault.py | 1 + 1 file changed, 1 insertion(+) diff --git a/skyflow/vault/controller/_vault.py b/skyflow/vault/controller/_vault.py index c05d81f0..a3b07528 100644 --- a/skyflow/vault/controller/_vault.py +++ b/skyflow/vault/controller/_vault.py @@ -139,6 +139,7 @@ def get(self, request: GetRequest): log_info(SkyflowMessages.Info.GET_REQUEST_RESOLVED.value, self.__vault_client.get_logger()) self.__initialize() records_api = self.__vault_client.get_records_api() + try: log_info(SkyflowMessages.Info.GET_TRIGGERED.value, self.__vault_client.get_logger()) api_response = records_api.record_service_bulk_get_record( From 7385eb084d92a281f9644c956ae1f57ee856dd6f Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 14 May 2025 13:29:34 +0000 Subject: [PATCH 20/24] [AUTOMATED] Private Release 2.0.0b2.dev0+3d817ab --- setup.py | 2 +- skyflow/utils/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 698c67fc..9fc1f06e 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ if sys.version_info < (3, 8): raise RuntimeError("skyflow requires Python 3.8+") -current_version = '2.0.0b2.dev0+3a80017' +current_version = '2.0.0b2.dev0+3d817ab' setup( name='skyflow', diff --git a/skyflow/utils/_version.py b/skyflow/utils/_version.py index a2802c11..f7eaf46f 100644 --- a/skyflow/utils/_version.py +++ b/skyflow/utils/_version.py @@ -1 +1 @@ -SDK_VERSION = '2.0.0b2.dev0+3a80017' \ No newline at end of file +SDK_VERSION = '2.0.0b2.dev0+3d817ab' \ No newline at end of file From 1816a92a62fd5fe5c58025bfd793c9603243181d Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Wed, 14 May 2025 20:14:34 +0530 Subject: [PATCH 21/24] SK-1911: add sky metadata headers --- skyflow/vault/controller/_vault.py | 30 ++++++++++---- tests/vault/controller/test__vault.py | 56 --------------------------- 2 files changed, 22 insertions(+), 64 deletions(-) diff --git a/skyflow/vault/controller/_vault.py b/skyflow/vault/controller/_vault.py index a3b07528..4602cf87 100644 --- a/skyflow/vault/controller/_vault.py +++ b/skyflow/vault/controller/_vault.py @@ -1,8 +1,10 @@ +import json from skyflow.generated.rest import V1FieldRecords, V1BatchRecord, V1TokenizeRecordRequest, \ V1DetokenizeRecordRequest from skyflow.utils import SkyflowMessages, parse_insert_response, \ handle_exception, parse_update_record_response, parse_delete_response, parse_detokenize_response, \ - parse_tokenize_response, parse_query_response, parse_get_response, encode_column_values + parse_tokenize_response, parse_query_response, parse_get_response, encode_column_values, get_metrics +from skyflow.utils.constants import SKY_META_DATA_HEADER from skyflow.utils.enums import RequestMethod from skyflow.utils.logger import log_info, log_error_log from skyflow.utils.validations import validate_insert_request, validate_delete_request, validate_query_request, \ @@ -61,6 +63,12 @@ def __build_insert_body(self, request: InsertRequest): records_list = self.__build_bulk_field_records(request.values, request.tokens) return records_list + def __get_headers(self): + headers = { + SKY_META_DATA_HEADER: json.dumps(get_metrics()) + } + return headers + def insert(self, request: InsertRequest): log_info(SkyflowMessages.Info.VALIDATE_INSERT_REQUEST.value, self.__vault_client.get_logger()) validate_insert_request(self.__vault_client.get_logger(), request) @@ -73,11 +81,11 @@ def insert(self, request: InsertRequest): log_info(SkyflowMessages.Info.INSERT_TRIGGERED.value, self.__vault_client.get_logger()) if request.continue_on_error: api_response = records_api.record_service_batch_operation(self.__vault_client.get_vault_id(), - records=insert_body, continue_on_error=request.continue_on_error, byot=request.token_mode.value) + records=insert_body, continue_on_error=request.continue_on_error, byot=request.token_mode.value, request_options=self.__get_headers()) else: api_response = records_api.record_service_insert_record(self.__vault_client.get_vault_id(), - request.table_name, records=insert_body,tokenization= request.return_tokens, upsert=request.upsert, homogeneous=request.homogeneous, byot=request.token_mode.value) + request.table_name, records=insert_body,tokenization= request.return_tokens, upsert=request.upsert, homogeneous=request.homogeneous, byot=request.token_mode.value, request_options=self.__get_headers()) insert_response = parse_insert_response(api_response, request.continue_on_error) log_info(SkyflowMessages.Info.INSERT_SUCCESS.value, self.__vault_client.get_logger()) @@ -104,7 +112,8 @@ def update(self, request: UpdateRequest): id=request.data.get("skyflow_id"), record=record, tokenization=request.return_tokens, - byot=request.token_mode.value + byot=request.token_mode.value, + request_options = self.__get_headers() ) log_info(SkyflowMessages.Info.UPDATE_SUCCESS.value, self.__vault_client.get_logger()) update_response = parse_update_record_response(api_response) @@ -124,7 +133,8 @@ def delete(self, request: DeleteRequest): api_response = records_api.record_service_bulk_delete_record( self.__vault_client.get_vault_id(), request.table, - skyflow_ids=request.ids + skyflow_ids=request.ids, + request_options=self.__get_headers() ) log_info(SkyflowMessages.Info.DELETE_SUCCESS.value, self.__vault_client.get_logger()) delete_response = parse_delete_response(api_response) @@ -154,6 +164,7 @@ def get(self, request: GetRequest): download_url=request.download_url, column_name=request.column_name, column_values=request.column_values, + request_options=self.__get_headers() ) log_info(SkyflowMessages.Info.GET_SUCCESS.value, self.__vault_client.get_logger()) get_response = parse_get_response(api_response) @@ -172,7 +183,8 @@ def query(self, request: QueryRequest): log_info(SkyflowMessages.Info.QUERY_TRIGGERED.value, self.__vault_client.get_logger()) api_response = query_api.query_service_execute_query( self.__vault_client.get_vault_id(), - query=request.query + query=request.query, + request_options=self.__get_headers() ) log_info(SkyflowMessages.Info.QUERY_SUCCESS.value, self.__vault_client.get_logger()) query_response = parse_query_response(api_response) @@ -199,7 +211,8 @@ def detokenize(self, request: DetokenizeRequest): api_response = tokens_api.record_service_detokenize( self.__vault_client.get_vault_id(), detokenization_parameters=tokens_list, - continue_on_error = request.continue_on_error + continue_on_error = request.continue_on_error, + request_options=self.__get_headers() ) log_info(SkyflowMessages.Info.DETOKENIZE_SUCCESS.value, self.__vault_client.get_logger()) detokenize_response = parse_detokenize_response(api_response) @@ -223,7 +236,8 @@ def tokenize(self, request: TokenizeRequest): log_info(SkyflowMessages.Info.TOKENIZE_TRIGGERED.value, self.__vault_client.get_logger()) api_response = tokens_api.record_service_tokenize( self.__vault_client.get_vault_id(), - tokenization_parameters=records_list + tokenization_parameters=records_list, + request_options=self.__get_headers() ) tokenize_response = parse_tokenize_response(api_response) log_info(SkyflowMessages.Info.TOKENIZE_SUCCESS.value, self.__vault_client.get_logger()) diff --git a/tests/vault/controller/test__vault.py b/tests/vault/controller/test__vault.py index ea59189e..39b44ae1 100644 --- a/tests/vault/controller/test__vault.py +++ b/tests/vault/controller/test__vault.py @@ -74,12 +74,6 @@ def test_insert_with_continue_on_error(self, mock_parse_response, mock_validate) # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.with_raw_response.record_service_batch_operation.assert_called_once_with( - VAULT_ID, - records=expected_body, - continue_on_error=True, - byot="DISABLE" - ) mock_parse_response.assert_called_once_with(mock_api_response, True) # Assert that the result matches the expected InsertResponse @@ -125,15 +119,6 @@ def test_insert_with_continue_on_error_false(self, mock_parse_response, mock_val # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.with_raw_response.record_service_insert_record.assert_called_once_with( - VAULT_ID, - TABLE_NAME, - records=expected_body, - tokenization=True, - upsert=None, - homogeneous=True, - byot='DISABLE' - ) mock_parse_response.assert_called_once_with(mock_api_response, False) # Assert that the result matches the expected InsertResponse @@ -192,15 +177,6 @@ def test_insert_with_continue_on_error_false_when_tokens_are_not_none(self, mock # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.with_raw_response.record_service_insert_record.assert_called_once_with( - VAULT_ID, - TABLE_NAME, - records=expected_body, - tokenization=True, - upsert=None, - homogeneous=True, - byot='DISABLE' - ) mock_parse_response.assert_called_once_with(mock_api_response, False) # Assert that the result matches the expected InsertResponse @@ -243,14 +219,6 @@ def test_update_successful(self, mock_parse_response, mock_validate): # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_update_record.assert_called_once_with( - VAULT_ID, - TABLE_NAME, - id="12345", - record=expected_record, - tokenization=True, - byot="DISABLE" - ) mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected UpdateResponse @@ -301,11 +269,6 @@ def test_delete_successful(self, mock_parse_response, mock_validate): # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_bulk_delete_record.assert_called_once_with( - VAULT_ID, - TABLE_NAME, - skyflow_ids=["12345", "67890"] - ) mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected DeleteResponse @@ -379,10 +342,6 @@ def test_get_successful(self, mock_parse_response, mock_validate): # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - records_api.record_service_bulk_get_record.assert_called_once_with( - VAULT_ID, - **expected_payload - ) mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected GetResponse @@ -435,7 +394,6 @@ def test_get_successful_with_column_values(self, mock_parse_response, mock_valid # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) records_api.record_service_bulk_get_record.assert_called_once() - mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected GetResponse self.assertEqual(result.data, expected_data) @@ -485,11 +443,6 @@ def test_query_successful(self, mock_parse_response, mock_validate): # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - query_api.query_service_execute_query.assert_called_once_with( - VAULT_ID, - query="SELECT * FROM test_table" - ) - mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected QueryResponse self.assertEqual(result.fields, expected_fields) @@ -554,11 +507,6 @@ def test_detokenize_successful(self, mock_parse_response, mock_validate): # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - tokens_api.with_raw_response.record_service_detokenize.assert_called_once_with( - VAULT_ID, - detokenization_parameters=expected_tokens_list, - continue_on_error=False - ) mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected DetokenizeResponse @@ -630,10 +578,6 @@ def test_tokenize_successful(self, mock_parse_response, mock_validate): # Assertions mock_validate.assert_called_once_with(self.vault_client.get_logger(), request) - tokens_api.record_service_tokenize.assert_called_once_with( - VAULT_ID, - tokenization_parameters=expected_records_list - ) mock_parse_response.assert_called_once_with(mock_api_response) # Check that the result matches the expected TokenizeResponse From f38a37c14656391308202f7c5a619cd2fda00a82 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Wed, 14 May 2025 14:45:17 +0000 Subject: [PATCH 22/24] [AUTOMATED] Private Release 2.0.0b2.dev0+1816a92 --- setup.py | 2 +- skyflow/utils/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 9fc1f06e..693812a0 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ if sys.version_info < (3, 8): raise RuntimeError("skyflow requires Python 3.8+") -current_version = '2.0.0b2.dev0+3d817ab' +current_version = '2.0.0b2.dev0+1816a92' setup( name='skyflow', diff --git a/skyflow/utils/_version.py b/skyflow/utils/_version.py index f7eaf46f..52222bf5 100644 --- a/skyflow/utils/_version.py +++ b/skyflow/utils/_version.py @@ -1 +1 @@ -SDK_VERSION = '2.0.0b2.dev0+3d817ab' \ No newline at end of file +SDK_VERSION = '2.0.0b2.dev0+1816a92' \ No newline at end of file From 625489617c2b143952114265807146507ac589ac Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Wed, 14 May 2025 20:19:30 +0530 Subject: [PATCH 23/24] SK-1911: add sky metadata header constant --- skyflow/utils/constants.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/skyflow/utils/constants.py b/skyflow/utils/constants.py index fea57008..d7e7a7f9 100644 --- a/skyflow/utils/constants.py +++ b/skyflow/utils/constants.py @@ -1,2 +1,3 @@ OPTIONAL_TOKEN='token' -PROTOCOL='https' \ No newline at end of file +PROTOCOL='https' +SKY_META_DATA_HEADER='sky-metadata' \ No newline at end of file From 97c924688f54aa1e2027935aac05dd76d710555a Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Wed, 14 May 2025 14:50:20 +0000 Subject: [PATCH 24/24] [AUTOMATED] Private Release 2.0.0b2.dev0+6254896 --- setup.py | 2 +- skyflow/utils/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 693812a0..d11a3346 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ if sys.version_info < (3, 8): raise RuntimeError("skyflow requires Python 3.8+") -current_version = '2.0.0b2.dev0+1816a92' +current_version = '2.0.0b2.dev0+6254896' setup( name='skyflow', diff --git a/skyflow/utils/_version.py b/skyflow/utils/_version.py index 52222bf5..2d4a9bc9 100644 --- a/skyflow/utils/_version.py +++ b/skyflow/utils/_version.py @@ -1 +1 @@ -SDK_VERSION = '2.0.0b2.dev0+1816a92' \ No newline at end of file +SDK_VERSION = '2.0.0b2.dev0+6254896' \ No newline at end of file