Skip to content

Commit e0a5957

Browse files
alexwolfmsftscottaddieannelo-msft
authored
Protocol methods doc (dotnet#41744)
New Protocol and Convenience methods doc --------- Co-authored-by: Scott Addie <[email protected]> Co-authored-by: Anne Thompson <[email protected]>
1 parent 52cd72c commit e0a5957

File tree

10 files changed

+306
-0
lines changed

10 files changed

+306
-0
lines changed

docs/azure/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@
8181
href: ./sdk/unit-testing-mocking.md
8282
- name: Configure a proxy server
8383
href: ./sdk/azure-sdk-configure-proxy.md
84+
- name: Library method types
85+
href: ./sdk/protocol-convenience-methods.md
8486
- name: Packages list
8587
href: ./sdk/packages.md
8688
- name: SDK example
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
---
2+
title: Understand Azure SDK client library method types
3+
description: Learn about the key differences between Azure SDK client library protocol and convenience methods
4+
ms.topic: conceptual
5+
ms.custom: devx-track-dotnet, engagement-fy23, devx-track-arm-template
6+
ms.date: 06/24/2024
7+
---
8+
9+
# Azure SDK for .NET protocol and convenience methods overview
10+
11+
The Azure SDK client libraries provide an interface to Azure services by translating method calls into messages sent via the respective service protocol. For REST API services, this means sending HTTP requests and converting the responses into runtime types. In this article, you'll learn about the different types of methods exposed by the client libraries and explore their implementation patterns.
12+
13+
## Understand protocol and convenience methods
14+
15+
An Azure SDK for .NET client library can expose two different categories of methods to make requests to an Azure service:
16+
17+
- **Protocol methods** provide a thin wrapper around the underlying REST API for a corresponding Azure service. These methods map primitive input parameters to HTTP request values and return a raw HTTP response object.
18+
19+
- **Convenience methods** provide a convenience layer over the lower-level protocol layer to add support for the .NET type system and other benefits. Convenience methods accept primitives or .NET model types as parameters and map them to the body of an underlying REST API request. These methods also handle various details of request and response management to allow developers to focus on sending and receiving data objects, instead of lower-level concerns.
20+
21+
### Azure SDK client library dependency patterns
22+
23+
Protocol and convenience methods implement slightly different patterns based on the underlying package dependency chain of the respective library. An Azure SDK for .NET client library depends on one of two different foundational libraries:
24+
25+
- [**Azure.Core**](/dotnet/api/overview/azure/core-readme) provides shared primitives, abstractions, and helpers for building modern Azure SDK client libraries. These libraries follow the [Azure SDK Design Guidelines for .NET](https://azure.github.io/azure-sdk/dotnet_introduction.html) and use package names and namespaces prefixed with *Azure*, such as [`Azure.Storage.Blobs`](/dotnet/api/overview/azure/storage.blobs-readme).
26+
27+
- [**System.ClientModel**](/dotnet/api/overview/azure/system.clientmodel-readme) is a core library that provides shared primitives, abstractions, and helpers for .NET service client libraries. The `System.ClientModel` library is a general purpose toolset designed to help build libraries for a variety of platforms and services, whereas the `Azure.Core` library is specifically designed for building Azure client libraries.
28+
29+
> [!NOTE]
30+
> The `Azure.Core` library itself also depends on `System.ClientModel` for various client building blocks. In the context of this article, the key differentiator for method patterns is whether a client library depends on `Azure.Core` or `System.ClientModel` directly, rather than through a transitive dependency.
31+
32+
The following table compares some of the request and response types used by protocol and convenience methods, based on whether the library depends on `Azure.Core` or `System.ClientModel`:
33+
34+
|Request or response concern |Azure.Core | System.ClientModel |
35+
|---------|---------|---------|
36+
|Request body | [`RequestContent`](/dotnet/api/azure.core.requestcontent) | [`BinaryContent`](/dotnet/api/system.clientmodel.binarycontent) |
37+
|Advanced options | [`RequestContext`](/dotnet/api/azure.requestcontext) | [`RequestOptions`](/dotnet/api/system.clientmodel.primitives.requestoptions) |
38+
|Raw HTTP Response | [`Response`](/dotnet/api/azure.response) | [`PipelineResponse`](/dotnet/api/system.clientmodel.primitives.pipelineresponse) |
39+
|Return type with output model | [`Response<T>`](/dotnet/api/azure.response-1) | [`ClientResult<T>`](/dotnet/api/system.clientmodel.clientresult-1) |
40+
41+
The sections ahead provide implementation examples of these concepts.
42+
43+
## Protocol and convenience method examples
44+
45+
The coding patterns and types used by client library protocol and convenience methods vary slightly based on whether the library depends on `Azure.Core` or `System.ClientModel`. The differences primarily influence the .NET types used for handling request and response data.
46+
47+
### Libraries that depend on Azure.Core
48+
49+
Azure SDK client libraries adhering to the [latest design guidelines](https://azure.github.io/azure-sdk/general_introduction.html) depend on the `Azure.Core` library. For example, the [`Azure.AI.ContentSafety`](/dotnet/api/overview/azure/ai.contentsafety-readme) library depends on the `Azure.Core` library and provides a `ContentSafetyClient` class that exposes both protocol and convenience methods.
50+
51+
### [Convenience method](#tab/convenience-methods)
52+
53+
The following code uses a `ContentSafetyClient` to call the `AnalyzeText` convenience method:
54+
55+
:::code source="snippets/protocol-convenience-methods/AzureCoreConvenience/Program.cs" highlight="10":::
56+
57+
The preceding code demonstrates the following `Azure.Core` convenience method patterns:
58+
59+
- Uses a standard C# primitive or model type as a parameter.
60+
- Returns a friendly C# type that represents the result of the operation.
61+
62+
### [Protocol method](#tab/protocol-methods)
63+
64+
The following code uses a `ContentSafetyClient` to call the `AnalyzeText` protocol method:
65+
66+
:::code source="snippets/protocol-convenience-methods/AzureCoreProtocol/Program.cs" highlight="18-23":::
67+
68+
The preceding code demonstrates the following protocol method patterns:
69+
70+
- Uses the `RequestContent` type to supply data for the request body.
71+
- Uses the `RequestContext` type to configure request options.
72+
- Returns data using the `Response` type.
73+
- Reads `response.Content` to access the response data.
74+
75+
> [!NOTE]
76+
> The preceding code configures the `ClientErrorBehaviors.NoThrow` for the `RequestOptions`. This option prevents non-success service responses status codes from throwing an exception, which means the app code should manually handle the response status code checks.
77+
78+
---
79+
80+
### Libraries that depend on System.ClientModel
81+
82+
Some client libraries that connect to non-Azure services use patterns similar to the libraries that depend on `Azure.Core`. For example, the [`OpenAI`](https://www.nuget.org/packages/OpenAI/2.0.0-beta.7) library provides a client that connects to the OpenAI services. These libraries are based on a library called `System.ClientModel` that has patterns similar to `Azure.Core`.
83+
84+
### [Convenience method](#tab/convenience-methods)
85+
86+
Consider the following code that uses a `ChatClient` to call the `CompleteChat` convenience method:
87+
88+
:::code source="snippets/protocol-convenience-methods/SCMConvenience/Program.cs" highlight="10,11":::
89+
90+
The preceding code demonstrates the following `System.ClientModel` convenience method patterns:
91+
92+
- Uses a standard C# primitive or model type as a parameter.
93+
- Returns a `ClientResult` type that represents the result of the operation.
94+
95+
### [Protocol method](#tab/protocol-methods)
96+
97+
The following code uses a `ChatClient` to call the `CompleteChat` protocol method:
98+
99+
:::code source="snippets/protocol-convenience-methods/SCMProtocol/Program.cs" highlight="26-31":::
100+
101+
The preceding code demonstrates the following `System.ClientModel` protocol method patterns:
102+
103+
- Uses the `BinaryContent` type as a parameter to supply data for the request body.
104+
- Uses the `RequestContext` type to configure request options.
105+
- Returns data using the `ClientResult` type.
106+
- Calls the `GetRawResponse` method to access the response data.
107+
108+
> [!NOTE]
109+
> The preceding code configures the [ClientErrorBehaviors.NoThrow](/dotnet/api/system.clientmodel.primitives.clienterrorbehaviors) behavior for the `RequestOptions`. This option prevents non-success service responses status codes from throwing an exception, which means the app code should manually handle the response status code checks.
110+
111+
---
112+
113+
## Protocol and convenience method usage guidance
114+
115+
Although the Azure SDK for .NET client libraries provide the option to use either protocol or convenience methods, prioritize using convenience methods in most scenarios. Convenience methods are designed to improve the development experience and provide flexibility for authoring requests and handling responses. However, both method types can be used in your app as needed. Consider the following criteria when deciding which type of method to use:
116+
117+
Convenience methods:
118+
119+
- Enable you to work with more friendly method parameter and response types.
120+
- Handle various low-level concerns and optimizations for you.
121+
122+
Protocol methods:
123+
124+
- Provide access to lower-level types, such as `RequestContext` and `RequestOptions`, which aren't available through convenience methods.
125+
- Enable access to features of the underlying REST APIs that convenience methods don't expose.
126+
- Enable you to create your own convenience methods around service endpoints that don't already have convenience methods. This approach requires understanding the service's REST API documentation to handle requests and responses correctly.
127+
128+
## See also
129+
130+
- [Understanding the Azure Core library for .NET](https://devblogs.microsoft.com/azure-sdk/understanding-the-azure-core-library-for-net/)
131+
- [Azure.Core library for .NET](/dotnet/api/overview/azure/core-readme)
132+
- [System.ClientModel library for .NET](/dotnet/api/overview/azure/system.clientmodel-readme)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net9.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="Azure.AI.ContentSafety" Version="1.0.0" />
12+
<PackageReference Include="Azure.Identity" Version="1.12.0" />
13+
</ItemGroup>
14+
15+
</Project>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
using Azure.AI.ContentSafety;
2+
using Azure.Identity;
3+
4+
// Create the client
5+
ContentSafetyClient safetyClient = new(
6+
new Uri("https://contentsafetyai.cognitiveservices.azure.com/"),
7+
new DefaultAzureCredential());
8+
9+
// Call the convenience method
10+
AnalyzeTextResult result = safetyClient.AnalyzeText("What is Microsoft Azure?");
11+
12+
// Display the results
13+
foreach (TextCategoriesAnalysis item in result.CategoriesAnalysis)
14+
{
15+
Console.WriteLine($"{item.Category}: {item.Severity}");
16+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net9.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="Azure.AI.ContentSafety" Version="1.0.0" />
12+
<PackageReference Include="Azure.Identity" Version="1.12.0" />
13+
</ItemGroup>
14+
15+
</Project>
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using Azure;
2+
using Azure.AI.ContentSafety;
3+
using Azure.Core;
4+
using Azure.Identity;
5+
6+
// Create the client
7+
ContentSafetyClient safetyClient = new(
8+
new Uri("https://contentsafetyai.cognitiveservices.azure.com/"),
9+
new DefaultAzureCredential());
10+
11+
// Create the prompt
12+
RequestContent prompt = RequestContent.Create(new
13+
{
14+
text = "What is Microsoft Azure?",
15+
});
16+
17+
// Call the protocol method
18+
Response response = safetyClient.AnalyzeText(
19+
prompt,
20+
new RequestContext()
21+
{
22+
ErrorOptions = ErrorOptions.NoThrow
23+
});
24+
25+
// Any non-200 response code from Azure AI Content Safety AnalyzeText REST API isn't considered a success response.
26+
// See REST API details at https://azure-ai-content-safety-api-docs.developer.azure-api.net/api-details#api=content-safety-service-2023-10-01&operation=TextOperations_AnalyzeText
27+
if (response.Status != 200)
28+
{
29+
throw new RequestFailedException(response);
30+
}
31+
32+
// Display the results
33+
Console.WriteLine(response.Content);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using OpenAI;
2+
using OpenAI.Chat;
3+
using System.ClientModel;
4+
5+
// Create the client
6+
OpenAIClient client = new("<your-openai-api-key>");
7+
ChatClient chatClient = client.GetChatClient("gpt-4");
8+
9+
// Call the convenience method
10+
ChatCompletion completion
11+
= chatClient.CompleteChat("What is Microsoft Azure?");
12+
13+
// Display the results
14+
Console.WriteLine($"{completion.Role}: {completion.Content}");
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net9.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="OpenAI" Version="2.0.0-beta.7" />
12+
</ItemGroup>
13+
14+
</Project>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using OpenAI;
2+
using OpenAI.Chat;
3+
using System.ClientModel;
4+
using System.ClientModel.Primitives;
5+
using System.Text.Json;
6+
7+
// Create the client
8+
OpenAIClient client = new("<your-openai-api-key>");
9+
ChatClient chatClient = client.GetChatClient("gpt-4");
10+
11+
// Create the request content
12+
BinaryData input = BinaryData.FromBytes("""
13+
{
14+
"model": "gpt-4o",
15+
"messages": [
16+
{
17+
"role": "user",
18+
"content": "What is Microsoft Azure?."
19+
}
20+
]
21+
}
22+
"""u8.ToArray());
23+
using BinaryContent content = BinaryContent.Create(input);
24+
25+
// Call the protocol method
26+
ClientResult result = chatClient.CompleteChat(
27+
content,
28+
new RequestOptions()
29+
{
30+
ErrorOptions = ClientErrorBehaviors.NoThrow
31+
});
32+
33+
PipelineResponse response = result.GetRawResponse();
34+
35+
// Any non-200 response code from CompleteChat endpoint isn't considered a success response.
36+
if (response.Status != 200)
37+
{
38+
throw new ClientResultException(response);
39+
}
40+
41+
// Display the results
42+
BinaryData output = result.GetRawResponse().Content;
43+
44+
using JsonDocument outputAsJson = JsonDocument.Parse(output);
45+
string message = outputAsJson.RootElement
46+
.GetProperty("choices"u8)[0]
47+
.GetProperty("message"u8)
48+
.GetProperty("content"u8)
49+
.GetString();
50+
51+
Console.WriteLine(message);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net9.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="OpenAI" Version="2.0.0-beta.7" />
12+
</ItemGroup>
13+
14+
</Project>

0 commit comments

Comments
 (0)