Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protocol methods doc #41744

Merged
merged 35 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
55e82ba
New protocol methods doc
alexwolfmsft Jun 21, 2024
fe3f119
updates
alexwolfmsft Jun 28, 2024
93cc572
protocol methods progress
alexwolfmsft Jul 11, 2024
15a8fb8
progress
alexwolfmsft Jul 12, 2024
fff65df
updates
alexwolfmsft Jul 12, 2024
dfcdd73
progress
alexwolfmsft Jul 12, 2024
d0e4701
restructure
alexwolfmsft Jul 12, 2024
e03ee0e
newline fix
alexwolfmsft Jul 12, 2024
bb36c6c
fixes
alexwolfmsft Jul 12, 2024
8b64a0b
fixes
alexwolfmsft Jul 12, 2024
22b239e
fix code block
alexwolfmsft Jul 12, 2024
a54c7e4
progress
alexwolfmsft Jul 12, 2024
f2b9e20
code fixes
alexwolfmsft Jul 12, 2024
ba41500
Apply suggestions from code review
alexwolfmsft Jul 12, 2024
d68c6b5
PR fixes
alexwolfmsft Jul 15, 2024
e741ef3
Merge branch 'protocol-methods-doc' of https://github.com/alexwolfmsf…
alexwolfmsft Jul 15, 2024
aa7242b
code samples added
alexwolfmsft Jul 15, 2024
5b1fb83
fixes
alexwolfmsft Jul 15, 2024
2e83917
fix code
alexwolfmsft Jul 15, 2024
6e1a23d
Apply suggestions from code review
alexwolfmsft Jul 15, 2024
52279d6
Apply suggestions from code review
alexwolfmsft Jul 15, 2024
167dfb9
fixes
alexwolfmsft Jul 15, 2024
7bfedd0
updates
alexwolfmsft Jul 15, 2024
034b486
fix linting
alexwolfmsft Jul 15, 2024
3633d1e
Apply suggestions from code review
alexwolfmsft Jul 16, 2024
76db3fb
Apply suggestions from code review
alexwolfmsft Jul 16, 2024
255844f
updates
alexwolfmsft Jul 16, 2024
aeaf5bd
fixes
alexwolfmsft Jul 16, 2024
d2d5ff1
fixes
alexwolfmsft Jul 16, 2024
cb78be2
Apply suggestions from code review
alexwolfmsft Jul 18, 2024
e15d859
tweak
alexwolfmsft Jul 18, 2024
2b2d3b2
Apply suggestions from code review
alexwolfmsft Jul 18, 2024
50362ca
changes
alexwolfmsft Jul 23, 2024
e4bdefa
updates
alexwolfmsft Jul 23, 2024
59ad892
fix code sample
alexwolfmsft Jul 23, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/azure/TOC.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@
href: ./sdk/unit-testing-mocking.md
- name: Configure a proxy server
href: ./sdk/azure-sdk-configure-proxy.md
- name: Protocol and convenience methods
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
href: ./sdk/protocol-convenience-methods.md
- name: Packages list
href: ./sdk/packages.md
- name: SDK example
Expand Down
209 changes: 209 additions & 0 deletions docs/azure/sdk/protocol-convenience-methods.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
---
title: Understand Azure SDK protocol methods
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
description: Learn about the key differences between Azure SDK protocol methods and convenience methods
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
ms.topic: conceptual
ms.custom: devx-track-dotnet, engagement-fy23, devx-track-arm-template
ms.date: 06/24/2024
---

# Azure SDK for .NET protocol and convenience methods overview

The Azure SDK client libraries provide an interface to Azure service REST APIs by translating method calls into underlying HTTP requests. In this article, you'll learn about the different types of methods exposed by the client libraries and explore their implementation patterns.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

## Understand protocol and convenience methods

The Azure SDK for .NET client libraries expose two different categories of methods to make requests to an Azure service:
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

- **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.

- **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 C# 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.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

### Azure SDK client library dependency patterns

Protocol and convenience methods implement slightly different patterns based on the underlying package dependency chain of the respective library. The Azure SDK for .NET client libraries depend on one of two different lower-level libraries:
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

- [**Azure.Core**](/dotnet/api/overview/azure/core-readme) provides shared primitives, abstractions, and helpers for building modern Azure SDK for .NET client libraries. These libraries follow the [Azure SDK Design Guidelines for .NET](https://azure.github.io/azure-sdk/dotnet_introduction.html) and use package and namespace names prefixed with 'Azure', such as [`Azure.Storage.Blobs`](/dotnet/api/overview/azure/storage.blobs-readme).
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

- [**System.ClientModel**](/dotnet/api/overview/azure/system.clientmodel-readme) is a lower-level 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.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

> [!NOTE]
> The `Azure.Core` library itself also depends on the `System.ClientModel` for various service 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 nested dependency.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

The following table compares some of the request and response types used by protocol and convenience methods based on whether the library depend on `Azure.Core` or `System.ClientModel`:
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

|Request or response concern |Azure.Core | System.ClientModel |
|---------|---------|---------|
|Request body | `RequestContent` | `BinaryContent` |
|Advanced options | `RequestContext` | `RequestOptions` |
|Raw HTTP Response | `Response` | `PipelineResponse` |
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
|Input model | `IPersistableModel<T>` | `IPersistableModel<T>` |
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
|Output model | `IPersistableModel<T>` | `IPersistableModel<T>` |
|Return type with output model | `Response<T>` | `ClientResult<T>` |

The sections ahead provide implementation examples of these concepts.

## Protocol and convenience method examples

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 C# types used for handling request and response data.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

### Libraries that depend on Azure.Core

Many Azure SDK client libraries 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.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

#### Work with protocol methods
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

The following code uses a `ContentSafetyClient` to call the `AnalyzeText` protocol method:

```csharp
// Create the client
var safetyClient = new ContentSafetyClient(
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
new Uri("content-safety-service-uri"),
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
new DefaultAzureCredential());

// Create the message content
RequestContent message = RequestContent.Create(new
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
{
text = "What is Microsoft Azure?",
});

// Call the protocol method
Response response = safetyClient.AnalyzeText(
message,
new RequestContext()
{
ErrorOptions = ErrorOptions.NoThrow;
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
});

// Display the response data
using (StreamReader streamReader = new StreamReader(response.ContentStream))
{
Console.WriteLine(streamReader.ReadToEnd());
}
```

The preceding code demonstrates the following protocol method patterns:

- Uses the `RequestContent` type as a to supply data for the request body.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
- Uses the `RequestContext` type to configure request options.
- Returns data using the `Response` type.
- Reads the `ContentStream` to access the response data.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

#### Work with convenience methods

The following code uses a `ContentSafetyClient` to call the `AnalyzeText` convenience method:

```csharp
// Create the client
var safetyClient = new ContentSafetyClient(
new Uri("content-safety-service-uri"),
new DefaultAzureCredential());

// Call the convenience method
AnalyzeTextResult result = safetyClient.AnalyzeText("What is Microsoft Azure?");

// Display the response data
foreach (var item in result.CategoriesAnalysis)
{
Console.Write($"{item.Category}: ");
Console.Write(item.Severity);
Console.WriteLine();
}
```

The preceding code demonstrates the following `Azure.Core` convenience method patterns:

- Uses a standard C# primitive or model type as a parameter.
- Returns a friendly C# type that represents the result of the operation.

### Libraries that depend on System.ClientModel

Some Azure client libraries depend directly on the `System.ClientModel` library. For example, the [`OpenAI`](https://www.nuget.org/packages/OpenAI/2.0.0-beta.7) library depends on the `System.ClientModel` library and provides a `ChatClient` class that exposes both protocol and convenience methods.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

#### Work with protocol methods

The following code uses a `ChatClient` to call the `CompleteChat` protocol method:

```csharp
// Create the client
OpenAIClient client = new("your-openai-key");
ChatClient chatClient = client.GetChatClient("gpt-4");

// Create the request prompt content
BinaryData prompt = BinaryData.FromBytes("""
{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "What is Microsoft Azure?."
}
]
}
"""u8.ToArray());
using BinaryContent content = BinaryContent.Create(prompt);

// Send the request
ClientResult result = chatClient.CompleteChat(
content,
new RequestOptions()
{
ErrorOptions = ClientErrorBehaviors.NoThrow
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
});

// Retrieve and display the response data
BinaryData output = result.GetRawResponse().Content;
using JsonDocument outputAsJson = JsonDocument.Parse(output);
string message = outputAsJson.RootElement
.GetProperty("choices"u8)[0]
.GetProperty("message"u8)
.GetProperty("content"u8)
.GetString();

Console.WriteLine(message);
```

The preceding code demonstrates the following `System.ClientModel` protocol method patterns:

- Uses the `BinaryContent` type as a parameter to supply data for the request body.
- Uses the `RequestContext` type to configure request options.
- Returns data using the `ClientResult` type.
- Calls the `GetRawResponse` method to access the response data.

#### Work with convenience methods

Consider the following code that uses a `ChatClient` to call the `CompleteChat` convenience method:

```csharp
// Create the client
OpenAIClient client = new("your-openai-key");
ChatClient chatClient = client.GetChatClient("gpt-4");

// Send the prompt
ClientResult<ChatCompletion> completion
= chatClient.CompleteChat("What is Azure?");

// Display the response data
Console.WriteLine($"{completion.Value.Role}: {completion.Value.Content}");
```

The preceding code demonstrates the following `System.ClientModel` convenience method patterns:

- Uses a standard C# primitive or model type as a parameter.
- Returns a `ClientResult` type that represents the result of the operation.

alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
## Protocol and convenience method usage guidance

Although the Azure SDK for .NET client libraries provide the option to use either protocol or convenience methods, in most scenarios developers should prioritize using convenience methods. Convenience methods are designed to improve the development experience and provide flexibility for authoring requests and handling responses. Consider the following criteria when deciding which type of method to use:
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

- Convenience methods:
- Enable you to work with more friendly method parameter and response types.
- Handle various low-level concerns and optimizations for you.

- Protocol methods:
- Provide access to lower-level types such as `RequestContext` and `RequestOptions` that are not available through convenience methods.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
- Enable access to features of the underlying REST APIs that convenience methods do not expose.
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved

## See also

- [Understanding the Azure Core library for .NET](https://devblogs.microsoft.com/azure-sdk/understanding-the-azure-core-library-for-net/)
- [System.ClientModel library for .NET](/dotnet/api/overview/azure/system.clientmodel-readme)
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
alexwolfmsft marked this conversation as resolved.
Show resolved Hide resolved
Loading