{"id":13787840,"url":"https://github.com/StyraInc/opa-csharp","last_synced_at":"2025-05-12T02:30:35.563Z","repository":{"id":226287903,"uuid":"768260346","full_name":"StyraInc/opa-csharp","owner":"StyraInc","description":"Styra's C# OPA Client SDK","archived":false,"fork":false,"pushed_at":"2024-04-19T18:24:31.000Z","size":114,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-04-19T21:15:14.636Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://styrainc.github.io/opa-csharp/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/StyraInc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2024-03-06T18:58:52.000Z","updated_at":"2024-06-20T20:21:01.653Z","dependencies_parsed_at":"2024-04-02T17:45:02.086Z","dependency_job_id":"878f197f-199c-4172-9efb-da56dbea577c","html_url":"https://github.com/StyraInc/opa-csharp","commit_stats":null,"previous_names":["styrainc/opa-csharp"],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StyraInc%2Fopa-csharp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StyraInc%2Fopa-csharp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StyraInc%2Fopa-csharp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StyraInc%2Fopa-csharp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/StyraInc","download_url":"https://codeload.github.com/StyraInc/opa-csharp/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225112957,"owners_count":17422831,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T21:00:32.231Z","updated_at":"2025-05-12T02:30:35.543Z","avatar_url":"https://github.com/StyraInc.png","language":"C#","funding_links":[],"categories":["Language and Platform Integrations"],"sub_categories":[".NET"],"readme":"# OPA C# SDK\n\n[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n[![NuGet Version](https://img.shields.io/nuget/v/Styra.Opa?style=flat\u0026color=%2324b6e0)](https://www.nuget.org/packages/Styra.Opa/)\n\n\u003e [!IMPORTANT]\n\u003e The documentation for this SDK lives at https://docs.styra.com/sdk, with reference documentation available at https://styrainc.github.io/opa-csharp\n\nYou can use the Styra OPA SDK to connect to [Open Policy Agent](https://www.openpolicyagent.org/) and [Enterprise OPA](https://www.styra.com/enterprise-opa/) deployments.\n\n## SDK Installation\n\n### Nuget\n\n```bash\ndotnet add package Styra.Opa\n```\n\u003c!-- No SDK Installation [installation] --\u003e\n\n## SDK Example Usage (high-level)\n\nAll the code examples that follow assume that the high-level SDK module has been imported, and that an `OpaClient` instance was created:\n\n```csharp\nusing Styra.Opa;\n\n\nprivate string serverURL = \"http://opa-host:8181\";\nprivate string path = \"authz/allow\";\nprivate OpaClient opa;\n\nopa = new OPAClient(serverURL);\n\nvar input = new Dictionary\u003cstring, object\u003e() {\n    { \"user\", \"alice\" },\n    { \"action\", \"read\" },\n    {\"resource\", \"/finance/reports/fy2038_budget.csv\"},\n};\n\n// (local variable) bool allowed\nvar allowed = await opa.check(\"authz/allow\", input);\n// (local variable) violations List\u003cstring\u003e?\nvar violations = await opa.evaluate\u003cList\u003cstring\u003e\u003e(\"authz/violations\", input);\n\n// Normal true/false cases...\nif (allowed) {\n    // ...\n} else {\n    Console.WriteLine(\"Violations: \" + violations);\n}\n```\n\n### Input types\n\nThe `check` and `evaluate` methods are overloaded for most standard JSON types, which include the following variants for the `input` parameter:\n\n| C# type | JSON equivalent type |\n| ------- | -------------------- |\n| `bool` | Boolean |\n| `double` | Number |\n| `string` | String |\n| `List\u003cobject\u003e` | Array |\n| `Dictionary\u003cstring, object\u003e` | Object |\n\n### Result Types\n\n#### `OpaClient.check`\nFor the `check` method, the output type is always `bool`.\n\n#### `OpaClient.evaluate\u003cT\u003e`\nFor the `evaluate` method, the output type is configurable using generics, as shown in the example below.\n\n```csharp\nstring path = \"authz/accounts/max_limit\";\n\ndouble maxLimit\ntry {\n    maxLimit = opa.evaluate\u003cdouble?\u003e(path, \"example\");\n}\ncatch (OpaException) {\n    maxLimit = 0.0f;\n}\n```\n\nNullable types are also allowed for output types, and if an error occurs during evaluation, a null result will be returned to the caller.\n\n```csharp\nstring path = \"authz/accounts/max_limit\";\n\ndouble? maxLimit = opa.evaluate\u003cdouble?\u003e(path, \"example\");\n```\n\nIf the selected return type `\u003cT\u003e` is possible to deserialize from the returned JSON, `evaluate\u003cT\u003e` will attempt to populate the variable with the value(s) present.\n\n```csharp\npublic struct AuthzStatus\n{\n    public AuthzStatus(bool allowed)\n    {\n        Allowed = allowed;\n    }\n\n    public double Allowed { get; }\n\n    public override string ToString() =\u003e $\"Application authorized: {Allowed}\";\n}\n\nvar input = new Dictionary\u003cstring, object\u003e() {\n    { \"user\", \"alice\" },\n    { \"action\", \"read\" },\n};\n\nAuthzStatus status;\ntry {\n    status = opa.evaluate\u003cAuthzStatus\u003e(path, input);\n}\ncatch (OpaException) {\n    status = new AuthzStatus(false);\n}\n```\n\n\u003e [!NOTE]\n\u003e For low-level SDK usage, see the sections below.\n\n---\n\n# OPA OpenAPI SDK (low-level)\n\n\u003c!-- Start Summary [summary] --\u003e\n## Summary\n\nFor more information about the API: [Enterprise OPA documentation](https://docs.styra.com/enterprise-opa)\n\u003c!-- End Summary [summary] --\u003e\n\n\u003c!-- Start Table of Contents [toc] --\u003e\n## Table of Contents\n\u003c!-- $toc-max-depth=2 --\u003e\n* [OPA C# SDK](#opa-c-sdk)\n  * [SDK Installation](#sdk-installation)\n  * [SDK Example Usage (high-level)](#sdk-example-usage-high-level)\n* [OPA OpenAPI SDK (low-level)](#opa-openapi-sdk-low-level)\n  * [SDK Example Usage](#sdk-example-usage)\n  * [Available Resources and Operations](#available-resources-and-operations)\n  * [Server Selection](#server-selection)\n  * [Error Handling](#error-handling)\n  * [Authentication](#authentication)\n  * [Community](#community)\n\n\u003c!-- End Table of Contents [toc] --\u003e\n\n\u003c!-- Start SDK Example Usage [usage] --\u003e\n## SDK Example Usage\n\n### Example 1\n\n```csharp\nusing Styra.Opa.OpenApi;\nusing Styra.Opa.OpenApi.Models.Components;\n\nvar sdk = new OpaApiClient();\n\nvar res = await sdk.ExecuteDefaultPolicyWithInputAsync(\n    input: Input.CreateNumber(\n        4963.69D\n    ),\n    pretty: false,\n    acceptEncoding: GzipAcceptEncoding.Gzip\n);\n\n// handle response\n```\n\n### Example 2\n\n```csharp\nusing Styra.Opa.OpenApi;\nusing Styra.Opa.OpenApi.Models.Requests;\n\nvar sdk = new OpaApiClient();\n\nExecutePolicyWithInputRequest req = new ExecutePolicyWithInputRequest() {\n    Path = \"app/rbac\",\n    RequestBody = new ExecutePolicyWithInputRequestBody() {\n        Input = Input.CreateBoolean(\n            false\n        ),\n    },\n};\n\nvar res = await sdk.ExecutePolicyWithInputAsync(req);\n\n// handle response\n```\n\n### Example 3\n\n```csharp\nusing Styra.Opa.OpenApi;\nusing Styra.Opa.OpenApi.Models.Components;\nusing Styra.Opa.OpenApi.Models.Requests;\nusing System.Collections.Generic;\n\nvar sdk = new OpaApiClient();\n\nExecuteBatchPolicyWithInputRequest req = new ExecuteBatchPolicyWithInputRequest() {\n    Path = \"app/rbac\",\n    RequestBody = new ExecuteBatchPolicyWithInputRequestBody() {\n        Inputs = new Dictionary\u003cstring, Input\u003e() {\n            { \"key\", Input.CreateStr(\n                \"\u003cvalue\u003e\"\n            ) },\n        },\n    },\n};\n\nvar res = await sdk.ExecuteBatchPolicyWithInputAsync(req);\n\n// handle response\n```\n\u003c!-- End SDK Example Usage [usage] --\u003e\n\n\u003c!-- Start Available Resources and Operations [operations] --\u003e\n## Available Resources and Operations\n\n\u003cdetails open\u003e\n\u003csummary\u003eAvailable methods\u003c/summary\u003e\n\n### [OpaApiClient SDK](docs/sdks/opaapiclient/README.md)\n\n* [ExecuteDefaultPolicyWithInput](docs/sdks/opaapiclient/README.md#executedefaultpolicywithinput) - Execute the default decision  given an input\n* [ExecutePolicy](docs/sdks/opaapiclient/README.md#executepolicy) - Execute a policy\n* [ExecutePolicyWithInput](docs/sdks/opaapiclient/README.md#executepolicywithinput) - Execute a policy given an input\n* [ExecuteBatchPolicyWithInput](docs/sdks/opaapiclient/README.md#executebatchpolicywithinput) - Execute a policy given a batch of inputs\n* [CompileQueryWithPartialEvaluation](docs/sdks/opaapiclient/README.md#compilequerywithpartialevaluation) - Partially evaluate a query\n* [Health](docs/sdks/opaapiclient/README.md#health) - Verify the server is operational\n\n\u003c/details\u003e\n\u003c!-- End Available Resources and Operations [operations] --\u003e\n\n\u003c!-- Start Server Selection [server] --\u003e\n## Server Selection\n\n### Override Server URL Per-Client\n\nThe default server can be overridden globally by passing a URL to the `serverUrl: string` optional parameter when initializing the SDK client instance. For example:\n```csharp\nusing Styra.Opa.OpenApi;\nusing Styra.Opa.OpenApi.Models.Components;\n\nvar sdk = new OpaApiClient(serverUrl: \"http://localhost:8181\");\n\nvar res = await sdk.ExecuteDefaultPolicyWithInputAsync(\n    input: Input.CreateNumber(\n        4963.69D\n    ),\n    pretty: false,\n    acceptEncoding: GzipAcceptEncoding.Gzip\n);\n\n// handle response\n```\n\u003c!-- End Server Selection [server] --\u003e\n\n\u003c!-- Start Error Handling [errors] --\u003e\n## Error Handling\n\nHandling errors in this SDK should largely match your expectations. All operations return a response object or throw an exception.\n\nBy default, an API error will raise a `Styra.Opa.OpenApi.Models.Errors.SDKException` exception, which has the following properties:\n\n| Property      | Type                  | Description           |\n|---------------|-----------------------|-----------------------|\n| `Message`     | *string*              | The error message     |\n| `StatusCode`  | *int*                 | The HTTP status code  |\n| `RawResponse` | *HttpResponseMessage* | The raw HTTP response |\n| `Body`        | *string*              | The response content  |\n\nWhen custom error responses are specified for an operation, the SDK may also throw their associated exceptions. You can refer to respective *Errors* tables in SDK docs for more details on possible exception types for each operation. For example, the `ExecuteDefaultPolicyWithInputAsync` method throws the following exceptions:\n\n| Error Type                                   | Status Code | Content Type     |\n| -------------------------------------------- | ----------- | ---------------- |\n| Styra.Opa.OpenApi.Models.Errors.ClientError  | 400, 404    | application/json |\n| Styra.Opa.OpenApi.Models.Errors.ServerError  | 500         | application/json |\n| Styra.Opa.OpenApi.Models.Errors.SDKException | 4XX, 5XX    | \\*/\\*            |\n\n### Example\n\n```csharp\nusing Styra.Opa.OpenApi;\nusing Styra.Opa.OpenApi.Models.Components;\nusing Styra.Opa.OpenApi.Models.Errors;\n\nvar sdk = new OpaApiClient();\n\ntry\n{\n    var res = await sdk.ExecuteDefaultPolicyWithInputAsync(\n        input: Input.CreateNumber(\n            4963.69D\n        ),\n        pretty: false,\n        acceptEncoding: GzipAcceptEncoding.Gzip\n    );\n\n    // handle response\n}\ncatch (Exception ex)\n{\n    if (ex is ClientError)\n    {\n        // Handle exception data\n        throw;\n    }\n    else if (ex is Models.Errors.ServerError)\n    {\n        // Handle exception data\n        throw;\n    }\n    else if (ex is Styra.Opa.OpenApi.Models.Errors.SDKException)\n    {\n        // Handle default exception\n        throw;\n    }\n}\n```\n\u003c!-- End Error Handling [errors] --\u003e\n\n\u003c!-- Start Authentication [security] --\u003e\n## Authentication\n\n### Per-Client Security Schemes\n\nThis SDK supports the following security scheme globally:\n\n| Name         | Type | Scheme      |\n| ------------ | ---- | ----------- |\n| `BearerAuth` | http | HTTP Bearer |\n\nTo authenticate with the API the `BearerAuth` parameter must be set when initializing the SDK client instance. For example:\n```csharp\nusing Styra.Opa.OpenApi;\nusing Styra.Opa.OpenApi.Models.Components;\n\nvar sdk = new OpaApiClient(bearerAuth: \"\u003cYOUR_BEARER_TOKEN_HERE\u003e\");\n\nvar res = await sdk.ExecuteDefaultPolicyWithInputAsync(\n    input: Input.CreateNumber(\n        4963.69D\n    ),\n    pretty: false,\n    acceptEncoding: GzipAcceptEncoding.Gzip\n);\n\n// handle response\n```\n\u003c!-- End Authentication [security] --\u003e\n\n\u003c!-- Placeholder for Future Speakeasy SDK Sections --\u003e\n\n## Community\n\nFor questions, discussions and announcements related to Styra products, services and open source projects, please join\nthe Styra community on [Slack](https://communityinviter.com/apps/styracommunity/signup)!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FStyraInc%2Fopa-csharp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FStyraInc%2Fopa-csharp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FStyraInc%2Fopa-csharp/lists"}