### Start OpenFGA with Docker Source: https://github.com/openfga/python-sdk/blob/main/example/streamed-list-objects/README.md Starts an OpenFGA server locally on port 8080 using Docker. This is a prerequisite for running the example. ```bash docker pull openfga/openfga && docker run -it --rm -p 8080:8080 openfga/openfga run ``` -------------------------------- ### Install OpenFGA SDK via Setuptools Source: https://github.com/openfga/python-sdk/blob/main/README.md Install the openfga_sdk package using Setuptools. This can be done for the current user or all users. ```sh python setup.py install --user ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/openfga/python-sdk/blob/main/example/opentelemetry/README.md Installs the necessary Python packages listed in `requirements.txt` for the example to run. ```bash pip install -r requirements.txt ``` -------------------------------- ### Run the Streamed List Objects Example Source: https://github.com/openfga/python-sdk/blob/main/example/streamed-list-objects/README.md Executes the Python example script that utilizes the `streamed_list_objects()` method. No additional setup is needed beyond having OpenFGA running. ```bash python example.py ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/openfga/python-sdk/blob/main/example/opentelemetry/README.md Copies the example environment file to be edited. Set OpenFGA and other relevant configurations in the `.env` file. ```bash cp .env.example .env ``` -------------------------------- ### Install OpenFGA SDK via pip Source: https://github.com/openfga/python-sdk/blob/main/README.md Install the openfga_sdk package from PyPI using pip. You may need root permissions. ```sh pip3 install openfga_sdk ``` -------------------------------- ### Run OpenFGA Python SDK Example Source: https://github.com/openfga/python-sdk/blob/main/example/opentelemetry/README.md Executes the main Python script that integrates the OpenFGA SDK with OpenTelemetry. ```bash python main.py ``` -------------------------------- ### Get Store Information Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Retrieve details about an OpenFGA store using its identifier. This example demonstrates how to configure the SDK with host and store ID, and how to authenticate using an API token. Ensure the configuration includes the correct host, scheme, and store ID. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint from openfga_sdk.models.credentials import Credentials from openfga_sdk.models.credential_configuration import CredentialConfiguration # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', credentials = credentials ) # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) try: # Get a store api_response = await api_instance.api_instance.get_store() pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->get_store: %s\n" % e) await api_client.close() ``` -------------------------------- ### Import OpenFGA SDK Source: https://github.com/openfga/python-sdk/blob/main/README.md Import the openfga_sdk package after installation. ```python import openfga_sdk ``` -------------------------------- ### Install OpenFGA SDK and OpenTelemetry Dependencies Source: https://github.com/openfga/python-sdk/blob/main/docs/opentelemetry.md Install the necessary Python packages for the OpenFGA SDK and OpenTelemetry, including a specific exporter like the OTLP gRPC exporter. ```sh pip install openfga opentelemetry-sdk ``` ```sh pip install opentelemetry-exporter-otlp-proto-grpc ``` -------------------------------- ### Install OpenFGA SDK from GitHub via pip Source: https://github.com/openfga/python-sdk/blob/main/README.md Install the openfga_sdk package directly from its GitHub repository using pip. You may need root permissions. ```sh pip3 install https://github.com/openfga/python-sdk.git ``` -------------------------------- ### Calling an Existing Endpoint with GET Source: https://github.com/openfga/python-sdk/blob/main/README.md Shows how to make a GET request to an existing OpenFGA endpoint, utilizing query parameters for filtering and pagination. ```APIDOC ## GET /stores ### Description Retrieves a list of stores with support for query parameters like pagination. ### Method GET ### Endpoint /stores ### Parameters #### Query Parameters - **page_size** (integer) - Optional - The number of items to return per page. - **continuation_token** (string) - Optional - A token for retrieving the next page of results. ### Request Example ```python stores_response = await fga_client.execute_api_request( operation_name="ListStores", method="GET", path="/stores", query_params={ "page_size": 10, "continuation_token": "eyJwayI6...", }, ) ``` ### Response #### Success Response (200) - **stores** (array) - A list of store objects. ``` -------------------------------- ### Read Authorization Model Example Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to read a specific version of an authorization model using its ID. Includes configuration for API host, store ID, and authentication. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', credentials = credentials ) # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) id = 'id_example' # str | try: # Return a particular version of an authorization model api_response = await api_instance.api_instance.read_authorization_model(id) pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->read_authorization_model: %s\n" % e) await api_client.close() ``` -------------------------------- ### Example Conventional Commits Source: https://github.com/openfga/python-sdk/blob/main/RELEASE.md Examples of commit messages following Conventional Commits format and their corresponding changelog entries. ```text feat: add support for batch check → Added fix: correct retry logic for transient errors → Fixed docs: update API reference → Documentation perf: cache DNS lookups → Changed refactor: extract auth helper → (hidden) chore: bump dependencies → (hidden) ``` -------------------------------- ### get_store Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Get a store. ```APIDOC ## GET /stores/{store_id} ### Description Get a store. ### Method GET ### Endpoint /stores/{store_id} ### Parameters #### Path Parameters - **store_id** (string) - Required - The ID of the store to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the store. - **name** (string) - The name of the store. - **description** (string) - The description of the store. - **created_at** (string) - The timestamp when the store was created. - **updated_at** (string) - The timestamp when the store was last updated. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "my-first-store", "description": "This is my first store", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Set up OpenTelemetry Collector Source: https://github.com/openfga/python-sdk/blob/main/example/opentelemetry/README.md Clones the repository for a pre-configured OpenTelemetry collector and starts it using Docker Compose. This collector will receive data from the OpenFGA SDK. ```bash git clone https://github.com/ewanharris/opentelemetry-collector-dev-setup.git cd opentelemetry-collector-dev-setup docker-compose up -d ``` -------------------------------- ### read Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Get tuples from the store that matches a query, without following userset rewrite rules. ```APIDOC ## POST /stores/{store_id}/read ### Description Get tuples from the store that matches a query, without following userset rewrite rules. ### Method POST ### Endpoint /stores/{store_id}/read ### Parameters #### Path Parameters - **store_id** (string) - Required - The ID of the store to read tuples from. #### Request Body - **user** (string) - Optional - Filter tuples by user. - **relation** (string) - Optional - Filter tuples by relation. - **object** (string) - Optional - Filter tuples by object. - **authorization_model_id** (string) - Optional - The ID of the authorization model to use for reading tuples. If not provided, the latest model will be used. ### Request Example ```json { "user": "user:anne", "relation": "member" } ``` ### Response #### Success Response (200) - **tuples** (array) - A list of tuples matching the query. - **user** (string) - The user part of the tuple. - **relation** (string) - The relation part of the tuple. - **object** (string) - The object part of the tuple. #### Response Example ```json { "tuples": [ { "user": "user:anne", "relation": "member", "object": "group:admin" } ] } ``` ``` -------------------------------- ### list_stores Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md List all stores. Returns a paginated list of OpenFGA stores and a continuation token to get additional stores. The continuation token will be empty if there are no more stores. ```APIDOC ## list_stores ### Description List all stores. Returns a paginated list of OpenFGA stores and a continuation token to get additional stores. The continuation token will be empty if there are no more stores. ### Method GET ### Endpoint /v1/stores ### Parameters No parameters are documented for this endpoint. ### Response #### Success Response (200) - **stores** (array) - A list of OpenFGA stores. - **continuation_token** (string) - A token to retrieve the next page of stores. #### Response Example ```json { "example": "response body" } ``` ### Authorization No authorization required ### HTTP request headers - **Accept**: application/json ### HTTP response details | Status code | Description | |-------------|-------------| | **200** | A successful response. | | **401** | Not authenticated. | | **403** | Forbidden. | | **404** | Request failed due to incorrect path. | | **500** | Request failed due to internal server error. | ``` -------------------------------- ### List Users with a Specific Relation to an Object Source: https://github.com/openfga/python-sdk/blob/main/README.md This example demonstrates how to list users who have a specific relation to a given object, supporting various user filters and contextual tuples. It uses an asynchronous context manager for the OpenFgaClient. ```python from openfga_sdk import OpenFgaClient from openfga_sdk.models.fga_object import FgaObject from openfga_sdk.client.models import ClientTuple from openfga_sdk.client.models.list_users_request import ClientListUsersRequest configuration = ClientConfiguration( api_url=FGA_API_URL, # ... ) async with OpenFgaClient(configuration) as api_client: options = { "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1" } request = ClientListUsersRequest( object=FgaObject(type="document", id="2021-budget"), relation="can_read", user_filters=[ UserTypeFilter(type="user"), UserTypeFilter(type="team", relation="member"), ], context={}, contextual_tuples=[ ClientTuple( user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation="editor", object="folder:product", ), ClientTuple( user="folder:product", relation="parent", object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a", ), ], ) response = await api_client.list_users(request, options) # response.users = [{object: {type: "user", id: "81684243-9356-4421-8fbf-a4f8d36aa31b"}}, {userset: { type: "user" }}, ...] ``` -------------------------------- ### Add Relationships using Write API Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Example of adding a new relationship (tuple) to the OpenFGA store. It specifies the user, relation, and object, and uses 'ignore' for duplicate entries. ```json { "writes": { "tuple_keys": [ { "user": "user:anne", "relation": "writer", "object": "document:2021-budget" } ], "on_duplicate": "ignore" }, "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC" } ``` -------------------------------- ### List Stores with Options Source: https://github.com/openfga/python-sdk/blob/main/README.md Shows how to list stores using the OpenFGA client, including optional parameters for pagination. This requires a client initialized with a configuration. ```python # from openfga_sdk.sync import OpenFgaClient # Initialize the fga_client # fga_client = OpenFgaClient(configuration) options = {"page_size": 25, "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="} response = await fga_client.list_stores(options) # response = ListStoresResponse(...) # response.stores = [Store({"id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z"})] ``` -------------------------------- ### Create a Store with OpenFGA Python SDK Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Shows how to create a new store in OpenFGA using the `create_store` method. This is necessary before you can define authorization models and tuples. The SDK requires host and authentication configuration. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", credentials = credentials ) # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) body = openfga_sdk.CreateStoreRequest() # CreateStoreRequest | try: # Create a store api_response = await api_instance.api_instance.create_store(body) pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->create_store: %s\n" % e) await api_client.close() ``` -------------------------------- ### Initialize Synchronous OpenFGA Client Source: https://github.com/openfga/python-sdk/blob/main/README.md Demonstrates how to initialize and use the synchronous OpenFGA client outside of an async context. Ensure you have the necessary configuration details like API URL, Store ID, and Model ID. ```python from openfga_sdk.client import ClientConfiguration from openfga_sdk.sync import OpenFgaClient def main(): configuration = ClientConfiguration( api_url=FGA_API_URL, # required store_id=FGA_STORE_ID, # optional, not needed when calling `CreateStore` or `ListStores` authorization_model_id=FGA_MODEL_ID, # optional, can be overridden per request ) # Enter a context with an instance of the OpenFgaClient with OpenFgaClient(configuration) as fga_client: api_response = fga_client.read_authorization_models() return api_response ``` -------------------------------- ### List Stores with OpenFgaApi Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to list stores using the OpenFgaApi. It shows configuration, authentication via API token, and handling API exceptions. Ensure the configuration includes the correct host and optional scheme. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", credentials = credentials ) # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) page_size = 56 # int | (optional) continuation_token = 'continuation_token_example' # str | (optional) name = 'name_example' # str | The name parameter instructs the API to only include results that match that name.Multiple results may be returned. Only exact matches will be returned; substring matches and regexes will not be evaluated (optional) try: # List all stores api_response = await api_instance.api_instance.list_stores(page_size=page_size, continuation_token=continuation_token, name=name) pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->list_stores: %s\n" % e) await api_client.close() ``` -------------------------------- ### Configure and Use OpenFgaApi ListUsers Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to configure the OpenFga SDK client with host, store ID, and authentication credentials, then call the ListUsers API. It includes error handling for API exceptions. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', credentials = credentials ) # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) body = openfga_sdk.ListUsersRequest() # ListUsersRequest | try: # List the users matching the provided filter who have a certain relation to a particular type. api_response = await api_instance.api_instance.list_users(body) pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->list_users: %s\n" % e) await api_client.close() ``` -------------------------------- ### Configure OpenFGA API Client Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Shows how to configure the OpenFGA API client with mandatory host and store ID, and optional scheme. Also demonstrates authentication using API tokens. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', credentials = credentials ) ``` -------------------------------- ### Call Existing Endpoint with GET Source: https://github.com/openfga/python-sdk/blob/main/README.md Use `execute_api_request` to call an existing GET endpoint, providing query parameters for filtering and pagination. The SDK handles URL encoding for parameters. ```python stores_response = await fga_client.execute_api_request( operation_name="ListStores", method="GET", path="/stores", query_params={ "page_size": 10, "continuation_token": "eyJwayI6...", }, ) stores = stores_response.json() print("Stores:", stores) ``` -------------------------------- ### Initialize OpenFgaClient with API Token Credentials Source: https://github.com/openfga/python-sdk/blob/main/README.md Initialize the OpenFgaClient with API token authentication. Ensure the FGA_API_TOKEN is correctly set. ```python from openfga_sdk import ClientConfiguration, OpenFgaClient from openfga_sdk.credentials import CredentialConfiguration, Credentials async def main(): configuration = ClientConfiguration( api_url=FGA_API_URL, # required store_id=FGA_STORE_ID, # optional, not needed when calling `CreateStore` or `ListStores` authorization_model_id=FGA_MODEL_ID, # Optional, can be overridden per request credentials=Credentials( method='api_token', configuration=CredentialConfiguration( api_token=FGA_API_TOKEN, ) ) ) # Enter a context with an instance of the OpenFgaClient async with OpenFgaClient(configuration) as fga_client: api_response = await fga_client.read_authorization_models() return api_response ``` -------------------------------- ### Configure and Read Changes Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to configure the OpenFGA client with API token authentication and then call the `read_changes` API to retrieve tuple changes. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', credentials = credentials ) # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) type = 'type_example' # str | (optional) page_size = 56 # int | (optional) continuation_token = 'continuation_token_example' # str | (optional) start_time = '2013-10-20T19:20:30+01:00' # datetime | Start date and time of changes to read. Format: ISO 8601 timestamp (e.g., 2022-01-01T00:00:00Z) If a continuation_token is provided along side start_time, the continuation_token will take precedence over start_time. (optional) try: # Return a list of all the tuple changes api_response = await api_instance.api_instance.read_changes(type=type, page_size=page_size, continuation_token=continuation_token, start_time=start_time) pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->read_changes: %s\n" % e) await api_client.close() ``` -------------------------------- ### OpenFgaApi.get_store Source: https://github.com/openfga/python-sdk/blob/main/README.md Get a specific store by its ID. This allows retrieval of store details. ```APIDOC ## GET /stores/{store_id} ### Description Get a store. ### Method GET ### Endpoint /stores/{store_id} ### Parameters #### Path Parameters - **store_id** (string) - Required - The ID of the store to retrieve. #### Query Parameters None #### Request Body None specified in source. ### Request Example None specified in source. ### Response #### Success Response (200) None specified in source. #### Response Example None specified in source. ``` -------------------------------- ### create_store Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Create a store. ```APIDOC ## POST /stores ### Description Create a store. ### Method POST ### Endpoint /stores ### Parameters #### Request Body - **name** (string) - Required - The name of the store to create. - **description** (string) - Optional - A description for the store. ### Request Example ```json { "name": "my-first-store", "description": "This is my first store" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created store. - **name** (string) - The name of the created store. - **description** (string) - The description of the created store. - **created_at** (string) - The timestamp when the store was created. - **updated_at** (string) - The timestamp when the store was last updated. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "my-first-store", "description": "This is my first store", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Get Store Information Source: https://github.com/openfga/python-sdk/blob/main/README.md Retrieves information about the current store. This method requires the client to be initialized with a store ID. ```python # from openfga_sdk import OpenFgaClient # Initialize the fga_client # fga_client = OpenFgaClient(configuration) response = await fga_client.get_store() # response = Store({"id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z"}) ``` -------------------------------- ### Create a New Store Source: https://github.com/openfga/python-sdk/blob/main/README.md Demonstrates how to create a new store with a given name. This operation does not require a pre-existing store ID. ```python # from openfga_sdk import CreateStoreRequest, OpenFgaClient # Initialize the fga_client # fga_client = OpenFgaClient(configuration) body = CreateStoreRequest( name = "FGA Demo Store", ) response = await fga_client.create_store(body) # response.id = "01FQH7V8BEG3GPQW93KTRFR8JB" ``` -------------------------------- ### OpenFgaApi.read Source: https://github.com/openfga/python-sdk/blob/main/README.md Get tuples from the store that matches a query, without following userset rewrite rules. Used for raw data retrieval. ```APIDOC ## POST /stores/{store_id}/read ### Description Get tuples from the store that matches a query, without following userset rewrite rules. ### Method POST ### Endpoint /stores/{store_id}/read ### Parameters #### Path Parameters - **store_id** (string) - Required - The ID of the store to read tuples from. #### Query Parameters None #### Request Body None specified in source. ### Request Example None specified in source. ### Response #### Success Response (200) None specified in source. #### Response Example None specified in source. ``` -------------------------------- ### List Objects with OpenFGA SDK Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to list objects of a given type that a user has a relation with using the OpenFGA Python SDK. Includes configuration for API host, store ID, and authentication via API token. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', credentials = credentials ) # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) body = openfga_sdk.ListObjectsRequest() # ListObjectsRequest | try: # List all objects of the given type that the user has a relation with api_response = await api_instance.api_instance.list_objects(body) pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->list_objects: %s\n" % e) await api_client.close() ``` -------------------------------- ### Configure OpenFGA Client with Custom Telemetry Source: https://github.com/openfga/python-sdk/blob/main/docs/opentelemetry.md Initialize the OpenFGA client with a custom TelemetryConfiguration to control which metrics and attributes are reported. If no configuration is provided, a default will be used. ```python from openfga_sdk.telemetry.configuration import ( TelemetryConfiguration, TelemetryMetricConfiguration, TelemetryMetricsConfiguration, ) from openfga_sdk import ClientConfiguration, OpenFgaClient configuration = ClientConfiguration( api_url=os.getenv("FGA_API_URL"), store_id=os.getenv("FGA_STORE_ID"), authorization_model_id=os.getenv("FGA_AUTHORIZATION_MODEL_ID"), # If you are comfortable with the default configuration outlined in the tables above, you can omit providing your own TelemetryConfiguration object, as one will be created for you. telemetry={ "metrics": { "fga-client.request.duration": { "fga-client.request.method": True, "http.response.status_code": True, }, }, }, ) fga = OpenFgaClient(configuration) ``` -------------------------------- ### Remove Relationships using Write API Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Example of removing an existing relationship (tuple) from the OpenFGA store. It specifies the user, relation, and object, and uses 'ignore' for missing entries. ```json { "deletes": { "tuple_keys": [ { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" } ], "on_missing": "ignore" } } ``` -------------------------------- ### Client Batch Check Initialization Source: https://github.com/openfga/python-sdk/blob/main/README.md This snippet shows the necessary imports and initialization for the `fga_client` before performing batch checks. It is intended for OpenFGA versions less than 1.8.0. ```python # from openfga_sdk import OpenFgaClient # from openfga_sdk.client import ClientCheckRequest # from openfga_sdk.client.models import ClientTuple # Initialize the fga_client ``` -------------------------------- ### Write Tuples with Conflict Options Source: https://github.com/openfga/python-sdk/blob/main/README.md This example shows how to configure conflict options for write operations, specifically to ignore duplicate writes and missing deletes. This is useful for ensuring idempotency. ```python # from openfga_sdk import OpenFgaClient # from openfga_sdk.client.models import ClientTuple, ClientWriteRequest # from openfga_sdk.client.models.write_conflict_opts import ( # ClientWriteRequestOnDuplicateWrites, # ClientWriteRequestOnMissingDeletes, # ConflictOptions, # ) options = { "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1", "conflict": ConflictOptions( on_duplicate_writes=ClientWriteRequestOnDuplicateWrites.IGNORE, # Available options: ERROR, IGNORE on_missing_deletes=ClientWriteRequestOnMissingDeletes.IGNORE, # Available options: ERROR, IGNORE ) } body = ClientWriteRequest( writes=[ ClientTuple( user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation="viewer", object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a", ), ], deletes=[ ClientTuple( user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation="writer", object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a", ), ], ) response = await fga_client.write(body, options) ``` -------------------------------- ### Stream List Objects with OpenFGA Python SDK Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to create an API client instance and use it to stream all objects of a given type that a user has a relation with. Includes error handling for API exceptions. ```python import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # Enter a context with an instance of the API client async with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openfga_sdk.OpenFgaApi(api_client) body = openfga_sdk.ListObjectsRequest() # ListObjectsRequest | try: # Stream all objects of the given type that the user has a relation with api_response = await api_instance.api_instance.streamed_list_objects(body) pprint(api_response) except ApiException as e: print("Exception when calling OpenFgaApi->streamed_list_objects: %s\n" % e) await api_client.close() ``` -------------------------------- ### BatchCheckRequest JSON Example Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md This JSON structure represents a batch check request, containing a list of checks, each with a tuple key, optional contextual tuples, context, and a unique correlation ID. ```json { "checks": [ { "tuple_key": { "object": "document:2021-budget" "relation": "reader", "user": "user:anne", }, "contextual_tuples": {...} "context": {} "correlation_id": "01JA8PM3QM7VBPGB8KMPK8SBD5" }, { "tuple_key": { "object": "document:2021-budget" "relation": "reader", "user": "user:bob", }, "contextual_tuples": {...} "context": {} "correlation_id": "01JA8PMM6A90NV5ET0F28CYSZQ" } ] } ``` -------------------------------- ### Read Changes Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Retrieves a list of tuple changes within a specified type. It supports pagination and can filter changes by time. If a continuation token is provided, it takes precedence over the start time. ```APIDOC ## GET /v1/changes ### Description Retrieves a list of tuple changes within a specified type. It supports pagination and can filter changes by time. If a continuation token is provided, it takes precedence over the start time. ### Method GET ### Endpoint /v1/changes ### Parameters #### Query Parameters - **type** (str) - Optional - The type of objects to read changes for. - **page_size** (int) - Optional - The maximum number of changes to return per page. - **continuation_token** (str) - Optional - A token to retrieve the next page of changes. Takes precedence over `start_time`. - **start_time** (datetime) - Optional - Start date and time of changes to read. Format: ISO 8601 timestamp (e.g., 2022-01-01T00:00:00Z). ### Response #### Success Response (200) - **ReadChangesResponse** (object) - Contains the list of changes and a continuation token if more changes are available. #### Response Example ```json { "changes": [ { "type": "user", "operation": "assign", "tuple_key": { "user": "user:anne", "relation": "member", "object": "group:engineering" }, "timestamp": "2023-10-20T19:20:30Z" } ], "continuation_token": "next_page_token" } ``` ### Error Handling - **400** - Request failed due to invalid input. - **401** - Not authenticated. - **403** - Forbidden. - **404** - Request failed due to incorrect path. - **409** - Request was aborted due a transaction conflict. - **422** - Request timed out due to excessive request throttling. - **500** - Request failed due to internal server error. ``` -------------------------------- ### Configure OpenFGA Client for Streaming Objects Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Sets up the OpenFGA client configuration, including API host, store ID, and API token authentication, which is a prerequisite for using the `streamed_list_objects` API. ```python import time import openfga_sdk from openfga_sdk.rest import ApiException from pprint import pprint # To configure the configuration # host is mandatory # api_scheme is optional and default to https # store_id is mandatory # See configuration.py for a list of all supported configuration parameters. configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', ) # When authenticating via the API TOKEN method credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) configuration = openfga_sdk.Configuration( scheme = "https", api_host = "api.fga.example", store_id = 'YOUR_STORE_ID', credentials = credentials ) ``` -------------------------------- ### Read Relationship Tuple Changes (Watch) Source: https://github.com/openfga/python-sdk/blob/main/README.md Reads historical relationship tuple writes and deletes. Options for page size and continuation token can be provided. The body requires a type and start time. ```python # from openfga_sdk import OpenFgaClient # from openfga_sdk.client.models import ClientReadChangesRequest # Initialize the fga_client # fga_client = OpenFgaClient(configuration) options = { # You can rely on the model id set in the configuration or override it for this specific request "page_size": "25", "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } body = ClientReadChangesRequest(type="document", start_time="2022-01-01T00:00:00Z") response = await fga_client.read_changes(body, options) # response.continuation_token = ... # response.changes = [TupleChange(tuple_key=TupleKey(object="...",relation="...",user="... "),operation=TupleOperation("TUPLE_OPERATION_WRITE"),timestamp=datetime.fromisoformat("..."))] ``` -------------------------------- ### OpenFgaApi.create_store Source: https://github.com/openfga/python-sdk/blob/main/README.md Create a new store. Stores are used to organize authorization models and data. ```APIDOC ## POST /stores ### Description Create a store. ### Method POST ### Endpoint /stores ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None specified in source. ### Request Example None specified in source. ### Response #### Success Response (200) None specified in source. #### Response Example None specified in source. ``` -------------------------------- ### BatchCheckResponse JSON Example Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md This JSON structure shows a typical response to a batch check request. The 'result' map uses the correlation_id from the request as keys to associate each check's outcome (allowed or error) with its corresponding request item. ```json { "result": { "01JA8PMM6A90NV5ET0F28CYSZQ": { "allowed": false, "error": {"message": ""} }, "01JA8PM3QM7VBPGB8KMPK8SBD5": { "allowed": true, "error": {"message": ""} } } } ``` -------------------------------- ### Configure Client Credentials Authentication Source: https://github.com/openfga/python-sdk/blob/main/README.md Use this configuration for client credentials authentication. Ensure all required environment variables are set. ```python from openfga_sdk import ClientConfiguration, OpenFgaClient from openfga_sdk.credentials import Credentials, CredentialConfiguration async def main(): configuration = ClientConfiguration( api_url=FGA_API_URL, # required store_id=FGA_STORE_ID, # optional, not needed when calling `CreateStore` or `ListStores` authorization_model_id=FGA_MODEL_ID, # Optional, can be overridden per request credentials=Credentials( method='client_credentials', configuration=CredentialConfiguration( api_issuer=FGA_API_TOKEN_ISSUER, api_audience=FGA_API_AUDIENCE, # optional, required for Auth0; omit for standard OAuth2 client_id=FGA_CLIENT_ID, client_secret=FGA_CLIENT_SECRET, # scopes="read write", # optional, space-separated OAuth2 scopes ) ) ) # Enter a context with an instance of the OpenFgaClient async with OpenFgaClient(configuration) as fga_client: api_response = await fga_client.read_authorization_models() return api_response ``` -------------------------------- ### Check API with Usersets and Model Difference Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Perform a check involving usersets where the authorization model includes a 'difference' operation. This example demonstrates how contextual tuples and model definitions interact to determine authorization, even when direct relationships are absent but implied through set operations. ```json { "tuple_key": { "user": "group:finance#member", "relation": "reader", "object": "document:2021-budget" }, "contextual_tuples": { "tuple_keys": [ { "user": "user:anne", "relation": "member", "object": "group:finance" }, { "user": "group:finance#member", "relation": "reader", "object": "document:2021-budget" }, { "user": "user:anne", "relation": "blocked", "object": "document:2021-budget" } ] } } ``` -------------------------------- ### write Source: https://github.com/openfga/python-sdk/blob/main/docs/OpenFgaApi.md Add or delete tuples from the store. ```APIDOC ## POST /stores/{store_id}/write ### Description Add or delete tuples from the store. ### Method POST ### Endpoint /stores/{store_id}/write ### Parameters #### Path Parameters - **store_id** (string) - Required - The ID of the store to write tuples to. #### Request Body - **writes** (array) - Optional - A list of tuples to add. - **user** (string) - Required - The user part of the tuple. - **relation** (string) - Required - The relation part of the tuple. - **object** (string) - Required - The object part of the tuple. - **deletes** (array) - Optional - A list of tuples to delete. - **user** (string) - Required - The user part of the tuple. - **relation** (string) - Required - The relation part of the tuple. - **object** (string) - Required - The object part of the tuple. - **authorization_model_id** (string) - Optional - The ID of the authorization model to use for writing tuples. If not provided, the latest model will be used. ### Request Example ```json { "writes": [ { "user": "user:anne", "relation": "member", "object": "group:admin" } ], "deletes": [ { "user": "user:bob", "relation": "member", "object": "group:admin" } ] } ``` ### Response #### Success Response (200) - ** FgaResponse** (object) - Contains information about the write operation. - ** FgaResponse** (object) - Contains the number of tuples written and deleted. - **writes_inserted** (integer) - The number of tuples inserted. - **writes_deleted** (integer) - The number of tuples deleted. #### Response Example ```json { " FgaResponse": { "writes_inserted": 1, "writes_deleted": 1 } } ``` ```