### Build and Run SDK Example Source: https://github.com/openfga/dotnet-sdk/blob/main/example/StreamedListObjectsExample/README.md Builds the .NET SDK and then runs the StreamedListObjects example from the SDK root directory. ```bash # From the SDK root directory, build the SDK first dotnet build src/OpenFga.Sdk/OpenFga.Sdk.csproj # Then run the example cd example/StreamedListObjectsExample dotnet run ``` -------------------------------- ### Example 1: Basic OpenFGA Operations Source: https://github.com/openfga/dotnet-sdk/blob/main/example/README.md A foundational example demonstrating store creation, model writing, tuple writing, and access checks using the OpenFGA .NET SDK. ```csharp using OpenFga.Sdk; using OpenFga.Sdk.Model; var client = new OpenFga.Sdk.OpenFgaClient(new ClientOptions() { ApiScheme = "http", ApiHost = "localhost:8080", StoreId = "my-store", Credentials = new NoCredentials() }); // Create a store var store = await client.CreateStoreAsync(new CreateStoreRequest("my-store")); // Define a model var model = await client.WriteModelAsync(new WriteModelRequest( store.Id, new UsersetTreeDefinition( new UsersetTreeDefinitionTypeDefinitions( "user", new UsersetTreeDefinitionRelations( new UsersetTreeDefinitionRelationsItems("user", "relation", "object")) ) ) )); // Write tuples await client.WriteTuplesAsync(new WriteTuplesRequest( store.Id, new WriteTuplesRequestTupleKeys(new WriteTuplesRequestTupleKeysItems("user:anne", "relation", "object:folder_1")) )); // Check access var check = await client.CheckAsync(new CheckRequest( store.Id, "user:anne", "relation", "object:folder_1" )); Console.WriteLine($"Check result: {check.ToObject().ToObject().Allowed}"); ``` -------------------------------- ### Basic OpenFGA SDK Request Example Source: https://github.com/openfga/dotnet-sdk/blob/main/example/ApiExecutorExample/README.md This C# code snippet demonstrates how to make a basic GET request to the /stores endpoint using the OpenFGA .NET SDK's ApiExecutor and RequestBuilder. It shows how to configure the request and process the response, including accessing the status code and the number of stores. ```csharp using OpenFga.Sdk.ApiClient; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; // Optional: Use an alias to avoid namespace/class name conflicts using FgaApiClient = OpenFga.Sdk.ApiClient.ApiClient; var client = new OpenFgaClient(config); var executor = client.ApiExecutor; var request = new RequestBuilder { Method = HttpMethod.Get, BasePath = config.ApiUrl, PathTemplate = "/stores", PathParameters = new Dictionary(), QueryParameters = new Dictionary() }; var response = await executor.ExecuteAsync( request, "ListStores" ); Console.WriteLine($"Status: {response.StatusCode}"); Console.WriteLine($"Stores: {response.Data.Stores.Count}"); ``` -------------------------------- ### Check .NET SDK Installation Source: https://github.com/openfga/dotnet-sdk/blob/main/example/ApiExecutorExample/README.md Verify that the .NET 8.0 SDK is installed on your system. This is a prerequisite for building and running .NET applications that use the SDK. ```bash dotnet --version ``` -------------------------------- ### Write Authorization Model Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Example demonstrating how to write a new authorization model using the OpenFGA .NET SDK. ```APIDOC ## POST /openfga/models ### Description Creates a new authorization model for the OpenFGA store. ### Method POST ### Endpoint /openfga/models ### Parameters #### Request Body - **body** (WriteAuthorizationModelRequest) - Required - The request body containing the authorization model to write. ### Request Example ```csharp var body = new WriteAuthorizationModelRequest(); ``` ### Response #### Success Response (201) - **WriteAuthorizationModelResponse** - A successful response. #### Response Example ```json { "example": "response body" } ``` ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json ### HTTP response details | Status code | Description | |-------------|-------------| | **201** | A successful response. | | **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. | ``` -------------------------------- ### Install OpenFGA .NET SDK using Package Manager Console Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Install the OpenFga.Sdk package using the Package Manager Console within Visual Studio. This is an alternative method for adding the SDK to your project. ```powershell Install-Package OpenFga.Sdk ``` -------------------------------- ### Read API Response Example Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Example of a response from the Read API, including a list of tuples and a continuation token for pagination. The continuation token is empty if there are no more results. ```json { "tuples": [ { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` -------------------------------- ### Run OpenFGA Server with Docker Source: https://github.com/openfga/dotnet-sdk/blob/main/example/ApiExecutorExample/README.md Starts an OpenFGA server instance in a Docker container, mapping port 8080 for access. ```bash docker run -d --name openfga-example -p 8080:8080 openfga/openfga:latest run ``` -------------------------------- ### Perform Write Operation using OpenFGA .NET SDK Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md This C# example demonstrates how to initialize the OpenFGA client and call the `Write` API to add or delete tuples. Ensure your environment variables for API scheme, host, and store ID are set. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class WriteExample { public static void Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(config, httpClient); var body = new WriteRequest(); // WriteRequest | try { // Add or delete tuples from the store Object response = await openFgaApi.Write(body); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.Write: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### StreamedListObjects Example Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md This example shows how to stream all objects of a given type that a user has a relation with using the `StreamedListObjects` method. ```APIDOC ## POST /openfga/dotnet-sdk/StreamedListObjects ### Description Streams all objects of the given type that the user has a relation with. ### Method POST ### Endpoint /openfga/dotnet-sdk/StreamedListObjects ### Parameters #### Request Body - **body** (ListObjectsRequest) - Required - The request body for listing objects. ### Request Example ```csharp var body = new ListObjectsRequest(); // Populate with necessary details await openFgaApi.StreamedListObjects(body); ``` ### Response #### Success Response (200) - **StreamResultOfStreamedListObjectsResponse** - A successful response containing streamed objects. #### Response Example ```json { "example": "StreamedListObjectsResponse example" } ``` ### 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 to a transaction conflict. - **422**: Request timed out due to excessive request throttling. - **500**: Request failed due to internal server error. ``` -------------------------------- ### Example Conventional Commits Source: https://github.com/openfga/dotnet-sdk/blob/main/RELEASE.md Examples of commit messages and their corresponding changelog entries. Ensure commit messages follow Conventional Commits format for correct grouping in the changelog. ```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 Information Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Retrieves information about the currently configured store. Requires the client to be initialized with a store ID. ```csharp var store = await fgaClient.GetStore(); ``` -------------------------------- ### Beta release versioning example Source: https://github.com/openfga/dotnet-sdk/blob/main/RELEASE.md When releasing betas, use the 'explicit' option to manually increment the pre-release suffix. This ensures release-please correctly tracks the version progression. ```text 0.11.0-beta.1 → explicit: 0.11.0-beta.2 → explicit: 0.11.0 ``` -------------------------------- ### Read Authorization Model Example Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to retrieve a specific version of an authorization model using its ID. Ensure your environment variables for API scheme, host, and store ID are set. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class ReadAuthorizationModelExample { public static void Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(config, httpClient); var id = "id_example"; // string | try { // Return a particular version of an authorization model ReadAuthorizationModelResponse response = await openFgaApi.ReadAuthorizationModel(id); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.ReadAuthorizationModel: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### Add OpenFGA .NET SDK using dotnet CLI Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Install the OpenFga.Sdk package using the .NET CLI. This command adds the SDK as a dependency to your project. ```powershell dotnet add package OpenFga.Sdk ``` -------------------------------- ### List Stores using OpenFGA .NET SDK Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md This C# code snippet demonstrates how to list all OpenFGA stores using the .NET SDK. It includes configuration setup, API client instantiation, and error handling for the ListStores API call. Ensure environment variables for API scheme and host are set. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class ListStoresExample { public static void Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(config, httpClient); var continuationToken = "continuationToken_example"; // string? | (optional) var name = "name_example"; // string? | 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 ListStoresResponse response = await openFgaApi.ListStores(continuationToken, name); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.ListStores: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### List Users with OpenFGA .NET SDK Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to call the ListUsers API using the OpenFGA .NET SDK. Ensure your OpenFGA connection details (API scheme, host, and store ID) are set as environment variables. This example includes basic error handling for API exceptions. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class ListUsersExample { public static async Task Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(configuration, httpClient); var body = new ListUsersRequest(); // ListUsersRequest | try { // List the users matching the provided filter who have a certain relation to a particular type. ListUsersResponse response = await openFgaApi.ListUsers(body); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.ListUsers: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### Read API Response Example with Multiple Relationships Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Example response showing multiple relationship tuples for a single object, including different relations and users. This demonstrates how the API returns all matching stored tuples. ```json { "tuples": [ { "key": { "user": "user:anne", "relation": "writer", "object": "document:2021-budget" }, "timestamp": "2021-10-05T13:42:12.356Z" }, { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` -------------------------------- ### GetStore API Source: https://github.com/openfga/dotnet-sdk/blob/main/README.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. ### Request Body (Details not provided in the source text) ### Response #### Success Response (200) (Details not provided in the source text) #### Response Example (Details not provided in the source text) ``` -------------------------------- ### Write Authorization Model (DSL) Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Creates a new authorization model using the OpenFGA DSL syntax. This example defines 'user' and 'document' types with 'writer' and 'viewer' relations. ```csharp var body = new ClientWriteAuthorizationModelRequest { SchemaVersion = "1.1", TypeDefinitions = new List { new() {Type = "user", Relations = new Dictionary()}, new() { Type = "document", Relations = new Dictionary { {"writer", new Userset {This = new object()}}, { "viewer", new Userset { Union = new Usersets { Child = new List { new() {This = new object()}, new() {ComputedUserset = new ObjectRelation {Relation = "writer"}} } } } } }, Metadata = new Metadata { Relations = new Dictionary { {"writer", new RelationMetadata { DirectlyRelatedUserTypes = new List { new() {Type = "user"} } }}, {"viewer", new RelationMetadata { DirectlyRelatedUserTypes = new List { new() {Type = "user"} } }} } } } } }; var response = await fgaClient.WriteAuthorizationModel(body); ``` -------------------------------- ### When to Use Custom API Requests vs. Standard SDK Methods Source: https://github.com/openfga/dotnet-sdk/blob/main/example/ApiExecutorExample/README.md This guide helps determine when to use the standard SDK methods versus the ApiExecutor.ExecuteAsync for custom requests, recommending standard methods for common operations and ApiExecutor for unlisted endpoints or when response details are needed. ```text ### Use Standard SDK Methods When: - The operation is available in the SDK (Check, Write, Read, etc.) - You don't need access to response headers - You want the simplest API ### Use ApiExecutor.ExecuteAsync When: - Calling endpoints not yet in the SDK - You need response headers or status codes - Building custom integrations - Need fine-grained control over requests - Working with experimental API features ``` -------------------------------- ### Get Store Information - C# Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Retrieve a specific OpenFGA store by its identifier. Ensure OpenFGA environment variables are configured. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class GetStoreExample { public static void Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(config, httpClient); try { // Get a store GetStoreResponse response = await openFgaApi.GetStore(); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.GetStore: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### Read API Source: https://github.com/openfga/dotnet-sdk/blob/main/README.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. ### Request Body (Details not provided in the source text) ### Response #### Success Response (200) (Details not provided in the source text) #### Response Example (Details not provided in the source text) ``` -------------------------------- ### Read API Source: https://github.com/openfga/dotnet-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 (Details not provided in the source text) ### Response #### Success Response (200) (Details not provided in the source text) #### Response Example (Details not provided in the source text) ``` -------------------------------- ### OpenFGA Custom API Requests Example Output Source: https://github.com/openfga/dotnet-sdk/blob/main/example/ApiExecutorExample/README.md This output shows the results of various custom API requests made using the OpenFGA .NET SDK, including listing stores, creating authorization models, writing and reading tuples, checking permissions, and handling raw JSON responses and custom headers. ```text === OpenFGA Custom API Requests Example === Example 1: List Stores Making GET request to /stores Status: OK Is Successful: True Found 0 store(s) Example 2: Create Store Making POST request to /stores Status: Created Store ID: 01JQWXYZ123ABC456DEF789GHJ Store Name: ApiExecutor-Example-1738713600000 Raw Response Length: 245 chars Example 3: Get Store Details Making GET request to /stores/{store_id} Status: OK Store Name: ApiExecutor-Example-1738713600000 Created At: 2025-02-04T10:00:00Z Response Headers: 8 Example 4: Create Authorization Model Making POST request to /stores/{store_id}/authorization-models Status: Created Model ID: 01JQWXYZ789DEF123ABC456GHJ Example 5: Write Relationship Tuples Making POST request to /stores/{store_id}/write Status: OK Tuples written successfully Example 6: Read Relationship Tuples Making POST request to /stores/{store_id}/read Status: OK Found 2 tuple(s): - user:alice is writer of document:roadmap - user:bob is reader of document:roadmap Example 7: Check Permission Making POST request to /stores/{store_id}/check Status: OK Allowed: True Example 8: Raw JSON Response Getting response as raw JSON string instead of typed object Status: OK Raw JSON (first 100 chars): {"stores":[],"continuation_token":""}... RawResponse and Data are the same: True Example 9: Custom Headers Making request with custom headers Status: OK Custom headers sent successfully Response has 8 headers Example 10: Fluent API for Request Building Using RequestBuilder with fluent methods Status: OK Found 0 store(s) Example 11: Streaming API Streaming list-objects for a computed relation via ExecuteStreamingAsync Created store: 01JQWXYZ... Created model: 01JQWXYZ... Writing tuples (1000 as owner, 1000 as viewer)... Wrote 2000 tuples Streaming objects via computed 'can_read' relation... - document:1 - document:2 - document:3 - document:500 - document:1000 - document:1500 - document:2000 Streamed 2000 objects Streaming demo store deleted Cleanup: Delete Store Making DELETE request to /stores/{store_id} Status: NoContent Store deleted successfully === All examples completed successfully! === ``` -------------------------------- ### List Objects Example Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Lists objects of a specific type that a user has access to. Configure the AuthorizationModelId, user, relation, type, and optionally provide contextual tuples. ```csharp var options = new ClientListObjectsOptions { // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1", }; var body = new ClientListObjectsRequest { User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation = "viewer", Type = "document", ContextualTuples = new List { new() { User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation = "writer", Object = "document:0192ab2d-d36e-7cb3-a4a8-5d1d67a300c5", }, }, }; var response = await fgaClient.ListObjects(body, options); ``` -------------------------------- ### OpenFGA Response for Authorization Model Creation Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Example JSON response from the OpenFGA API after successfully creating an authorization model, including the authorization model ID. ```json {"authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC"} ``` -------------------------------- ### Client Batch Check Example Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Run multiple checks in parallel on the client side. Useful for small batches (< 10 checks) when individual request control is needed. Configure the AuthorizationModelId and MaxParallelRequests. ```csharp var options = new ClientBatchCheckClientOptions { AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1", MaxParallelRequests = 5, // Max number of requests to issue in parallel, defaults to 10 }; var body = new List() { new() { User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation = "viewer", Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a", }, new() { User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation = "admin", Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a", } }; var response = await fgaClient.ClientBatchCheck(body, options); ``` -------------------------------- ### Perform Check Request in C# Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Example of how to use the `OpenFgaApi.Check` method to determine if a user is authorized for an object. Requires proper SDK configuration and a populated `CheckRequest` object. Includes basic error handling for `ApiException`. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class CheckExample { public static async Task Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(configuration, httpClient); var body = new CheckRequest(); // CheckRequest | try { // Check whether a user is authorized to access an object CheckResponse response = await openFgaApi.Check(body); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.Check: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### Create OpenFGA Store in C# Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to create a new OpenFGA store using the `OpenFgaApi.CreateStore` method. This is useful for setting up a new environment for authorization models and tuples. Ensure the SDK is configured correctly. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class CreateStoreExample { public static async Task Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(configuration, httpClient); try { // Create a store CreateStoreResponse response = await openFgaApi.CreateStore(); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.CreateStore: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### OpenTelemetryExample: SDK Observability Source: https://github.com/openfga/dotnet-sdk/blob/main/example/README.md Shows how to integrate OpenTelemetry for observability and tracing of OpenFGA SDK operations. This requires setting up OpenTelemetry providers. ```csharp using OpenTelemetry.Trace; using OpenFga.Sdk; using OpenFga.Sdk.Model; // Configure OpenTelemetry tracing var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource("OpenFga.Sdk") .Build(); var client = new OpenFga.Sdk.OpenFgaClient(new ClientOptions() { ApiScheme = "http", ApiHost = "localhost:8080", StoreId = "my-store", Credentials = new NoCredentials() }); // Perform an operation that will be traced var check = await client.CheckAsync(new CheckRequest( "my-store", "user:anne", "relation", "object:folder_1" )); Console.WriteLine($"Check result: {check.ToObject().ToObject().Allowed}"); tracerProvider.Dispose(); ``` -------------------------------- ### Initialize OpenFGA Client with OpenTelemetry Source: https://github.com/openfga/dotnet-sdk/blob/main/OpenTelemetry.md Sets up OpenTelemetry metrics and initializes the OpenFGA client with default configuration. Ensure environment variables for API URL, Store ID, and Model ID are set. ```csharp using OpenFga.Sdk.Client; using OpenFga.Sdk.Client.Model; using OpenFga.Sdk.Model; using OpenFga.Sdk.Telemetry; using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; using System.Diagnostics; namespace Example { public class Example { public static async Task Main() { try { // Setup OpenTelemetry Metrics using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddHttpClientInstrumentation() // To instrument the default http client .AddMeter(Metrics.Name) // .AddMeter("OpenFga.Sdk") also works .ConfigureResource(resourceBuilder => resourceBuilder.AddService("openfga-dotnet-example")) .AddOtlpExporter() // Required to export to an OTLP compatible endpoint .AddConsoleExporter() // Only needed to export the metrics to the console (e.g. when debugging) .Build(); // Configure the OpenFGA SDK with default configuration (default metrics and attributes will be enabled) var configuration = new ClientConfiguration() { ApiUrl = Environment.GetEnvironmentVariable("FGA_API_URL"), StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"), AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_MODEL_ID"), // Credentials = ... // If needed }; var fgaClient = new OpenFgaClient(configuration); // Call the SDK normally var response = await fgaClient.ReadAuthorizationModels(); } catch (ApiException e) { Debug.Print("Error: "+ e); } } } } ``` -------------------------------- ### Initialize OpenFgaClient without Credentials Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Demonstrates how to initialize the `OpenFgaClient` with basic configuration, including API URL and Store ID. The client automatically retries requests on specific error codes. Ensure the `ApiUrl` is set, and optionally provide `StoreId` and `AuthorizationModelId`. ```csharp using OpenFga.Sdk.Client; using OpenFga.Sdk.Client.Model; using OpenFga.Sdk.Model; namespace Example { public class Example { public static async Task Main() { try { var configuration = new ClientConfiguration() { ApiUrl = Environment.GetEnvironmentVariable("FGA_API_URL") ?? "http://localhost:8080", // required, e.g. https://api.fga.example StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_MODEL_ID"), // Optional, can be overridden per request }; var fgaClient = new OpenFgaClient(configuration); var response = await fgaClient.ReadAuthorizationModels(); } catch (ApiException e) { Debug.Print("Error: "+ e); } } } } ``` -------------------------------- ### Verify OpenFGA Server Health Source: https://github.com/openfga/dotnet-sdk/blob/main/example/ApiExecutorExample/README.md Checks if the OpenFGA server is running and accessible by sending a GET request to the /healthz endpoint. ```bash curl http://localhost:8080/healthz ``` -------------------------------- ### List Objects with OpenFGA .NET SDK Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to use the ListObjects API to find all objects of a given type that a user is related to. Ensure your OpenFGA connection details are set as environment variables. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class ListObjectsExample { public static void Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(config, httpClient); var body = new ListObjectsRequest(); // ListObjectsRequest | try { // List all objects of the given type that the user has a relation with ListObjectsResponse response = await openFgaApi.ListObjects(body); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.ListObjects: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### Expand Relationships Example Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Expands relationships in a userset tree format. Configure the AuthorizationModelId and specify the relation, object, and contextual tuples for the expansion. ```csharp var options = new ClientCheckOptions { // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1", }; var body = new ClientExpandRequest { Relation = "viewer", Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a", }; var response = await fgaClient.Expand(body, options); ``` -------------------------------- ### Authorization Model JSON Response Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Example JSON response structure for a successful authorization model read operation, detailing type definitions and relations. ```json { "authorization_model":{ "id":"01G5JAVJ41T49E9TT3SKVS7X1J", "type_definitions":[ { "type":"user" }, { "type":"document", "relations":{ "reader":{ "union":{ "child":[ { "this":{} }, { "computedUserset":{ "object":"", "relation":"writer" } } ] } }, "writer":{ "this":{} } } } ] } } ``` -------------------------------- ### List Stores with Options Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Retrieves a paginated list of stores. Supports specifying page size and continuation token for pagination. ```csharp var options = new ClientListStoresOptions { PageSize = 10, ContinuationToken = "...", }; var response = await fgaClient.ListStores(options); ``` -------------------------------- ### Create Authorization Model JSON Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Example JSON payload for creating a new authorization model with 'user' and 'document' type definitions, including 'reader' and 'writer' relations. ```json { "type_definitions":[ { "type":"user" }, { "type":"document", "relations":{ "reader":{ "union":{ "child":[ { "this":{} }, { "computedUserset":{ "object":"", "relation":"writer" } } ] } }, "writer":{ "this":{} } } } ] } ``` -------------------------------- ### Example JSON Response with Empty Continuation Token Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md This JSON structure indicates the end of the authorization models list for a store. The `continuation_token` field is empty when no more models are available. ```json { "authorization_models": [ { "id": "01G50QVV17PECNVAHX1GG4Y5NC", "type_definitions": [...] }, { "id": "01G4ZW8F4A07AKQ8RHSVG9RW04", "type_definitions": [...] }, ], "continuation_token": "" } ``` -------------------------------- ### Create a New Store Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Initializes a new store with a given name. The store ID can then be used to configure the client for subsequent operations. ```csharp var store = await fgaClient.CreateStore(new ClientCreateStoreRequest(){Name = "FGA Demo"}) // store.Id = "01FQH7V8BEG3GPQW93KTRFR8JB" // store store.Id in database // update the storeId of the current instance fgaClient.StoreId = storeId; // continue calling the API normally ``` -------------------------------- ### CreateStore API Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Create a store. ```APIDOC ## POST /stores ### Description Create a store. ### Method POST ### Endpoint /stores ### Parameters (Details not provided in the source text) ### Request Body (Details not provided in the source text) ### Response #### Success Response (200) (Details not provided in the source text) #### Response Example (Details not provided in the source text) ``` -------------------------------- ### BatchCheckResponse Example (JSON) Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md This JSON structure represents a response from the BatchCheck API. The results are mapped by the `correlation_id` provided in the request, indicating whether each check was allowed or if an error occurred. ```json { "result": { "01JA8PMM6A90NV5ET0F28CYSZQ": { "allowed": false, "error": {"message": ""} }, "01JA8PM3QM7VBPGB8KMPK8SBD5": { "allowed": true, "error": {"message": ""} } } } ``` -------------------------------- ### CreateStore API Source: https://github.com/openfga/dotnet-sdk/blob/main/README.md Create a store. ```APIDOC ## POST /stores ### Description Create a store. ### Method POST ### Endpoint /stores ### Parameters #### Query Parameters (Details not provided in the source text) #### Request Body (Details not provided in the source text) ### Response #### Success Response (200) (Details not provided in the source text) #### Response Example (Details not provided in the source text) ``` -------------------------------- ### BatchCheckRequest Example (JSON) Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md This JSON structure represents a request to the BatchCheck API, containing a list of checks with their respective tuple keys, contextual tuples, and unique correlation IDs. ```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" } ] } ``` -------------------------------- ### Stream Objects with OpenFGA .NET SDK Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to stream objects of a given type that a user has a relation with. Ensure environment variables for API scheme, host, and store ID are set. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class StreamedListObjectsExample { public static void Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(config, httpClient); var body = new ListObjectsRequest(); // ListObjectsRequest | try { // Stream all objects of the given type that the user has a relation with StreamResultOfStreamedListObjectsResponse response = await openFgaApi.StreamedListObjects(body); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.StreamedListObjects: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ``` -------------------------------- ### Read Tuple Changes with OpenFGA .NET SDK Source: https://github.com/openfga/dotnet-sdk/blob/main/docs/OpenFgaApi.md Demonstrates how to call the ReadChanges API to retrieve tuple modifications. Configure the SDK with your OpenFGA host and store ID. Handles potential API exceptions. ```csharp using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using OpenFga.Sdk.Api; using OpenFga.Sdk.Client; using OpenFga.Sdk.Configuration; using OpenFga.Sdk.Model; namespace Example { public class ReadChangesExample { public static void Main() { var configuration = new Configuration() { ApiScheme = Environment.GetEnvironmentVariable("OPENFGA_API_SCHEME"), // optional, defaults to "https" ApiHost = Environment.GetEnvironmentVariable("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example) StoreId = Environment.GetEnvironmentVariable("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }; HttpClient httpClient = new HttpClient(); var openFgaApi = new OpenFgaApi(config, httpClient); var type = "type_example"; // string? | (optional) var pageSize = 56; // int? | (optional) var continuationToken = "continuationToken_example"; // string? | (optional) var startTime = DateTime.Parse("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 ReadChangesResponse response = await openFgaApi.ReadChanges(type, pageSize, continuationToken, startTime); Debug.WriteLine(response); } catch (ApiException e) { Debug.Print("Exception when calling OpenFgaApi.ReadChanges: " + e.Message ); Debug.Print("Status Code: "+ e.ErrorCode); Debug.Print(e.StackTrace); } } } } ```