Introduction
AI agents extend traditional chat applications by combining a language model with developer-defined tools. A tool can retrieve data from a REST endpoint, perform a calculation, create a service request, or execute another controlled business operation. The model decides when a tool is needed, but the ASP.NET Core application remains responsible for authentication, authorization, validation, execution, and auditing.
This guide demonstrates how to integrate an AI agent with external REST APIs by using ASP.NET Core and Azure OpenAI. The practical example implements an Order Support Agent that can look up a customer, retrieve the latest order, check shipment status, and return a concise response. The design can be adapted for employee services, IT support, finance operations, CRM workflows, and other enterprise use cases.
What the Solution Will Do
Accept a natural-language request through an ASP.NET Core endpoint.
Send the request and available tool definitions to an Azure OpenAI deployment.
Detect and validate tool calls selected by the model.
Call approved downstream REST APIs through typed HttpClient services.
Return tool results to the model and produce a final response.
Apply enterprise controls such as Microsoft Entra ID, managed identity, logging, retries, and human approval for sensitive actions.
Prerequisites
Requirement | Recommended baseline |
|---|---|
Development environment | Visual Studio 2022 or Visual Studio Code with the current supported .NET SDK |
Azure services | Azure OpenAI resource with a deployed chat-capable model |
Authentication | Microsoft Entra ID and DefaultAzureCredential for keyless access |
Packages | Azure.AI.OpenAI, Azure.Identity, Microsoft.Extensions.Http.Resilience, Swashbuckle.AspNetCore |
REST API | An accessible API with documented request and response contracts |
Operational tooling | Application Insights or OpenTelemetry-compatible, monitoring |
Important: model and SDK availability can differ by Azure region and subscription. Use the deployment name configured in your Azure OpenAI resource, not a hard-coded model marketing name.
Solution Architecture
The recommended architecture keeps model reasoning separate from business-system access. The agent never receives unrestricted network or database access. It can invoke only the tool contracts explicitly registered by the application.
Stage | Component | Responsibility |
|---|---|---|
1 | Client | Sends a user objective and optional conversation identifier. |
2 | ASP.NET Core API | Authenticates the caller, validates input, and starts the agent workflow. |
3 | Agent orchestration service | Builds instructions, tool definitions, conversation context, and model requests. |
4 | Azure OpenAI | Produces either a normal response or one or more structured tool calls. |
5 | Tool dispatcher | Maps approved tool names to application methods and validates arguments. |
6 | REST API client | Uses HttpClientFactory to call customer, order, or shipment services. |
7 | Agent response | Sends tool output back to the model and returns the final answer to the client. |
Request Flow
The user asks: “Find the latest order for customer C1024 and tell me whether it has shipped.”
The model selects GetLatestOrder with customerId C1024.
The dispatcher validates the arguments and calls the Order API.
The Order API returns order O-45821.
The model selects GetShipmentStatus with orderId O-45821.
The Shipment API returns InTransit with an estimated delivery date.
The agent summarizes the result without exposing internal JSON or credentials.
Suggested Project Structure
OrderSupport.AgentApi/
Agents/
OrderSupportAgent.cs
ToolDispatcher.cs
Controllers/
AgentController.cs
Models/
AgentRequest.cs
AgentResponse.cs
OrderDto.cs
ShipmentStatusDto.cs
Services/
IOrderApiClient.cs
OrderApiClient.cs
Options/
AzureOpenAIOptions.cs
OrderApiOptions.cs
Program.cs
appsettings.jsonKey Design Rule
Treat tool calls as untrusted input. The model may propose a tool name and arguments, but server-side code must authorize the caller, validate the schema, apply business rules, and reject any operation outside the approved tool catalog.
Create the ASP.NET Core Web API
dotnet new webapi -n OrderSupport.AgentApi
dotnet new sln -n OrderSupport
dotnet sln add OrderSupport.AgentApi/OrderSupport.AgentApi.csproj
cd OrderSupport.AgentApi
dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.Http.Resilience
dotnet add package Swashbuckle.AspNetCoreConfiguration
{
"AzureOpenAI": {
"Endpoint": "https://<resource-name>.openai.azure.com/",
"DeploymentName": "<deployment-name>"
},
"OrderApi": {
"BaseUrl": "https://api.contoso.example/",
"TimeoutSeconds": 15
}
}Do not store production API keys, bearer tokens, or passwords in appsettings.json. Prefer managed identity and Microsoft Entra ID. For local development, DefaultAzureCredential can use the signed-in Azure CLI or Visual Studio identity.
Options Classes
public sealed class AzureOpenAIOptions
{
public const string SectionName = "AzureOpenAI";
public required Uri Endpoint { get; init; }
public required string DeploymentName { get; init; }
}
public sealed class OrderApiOptions
{
public const string SectionName = "OrderApi";
public required Uri BaseUrl { get; init; }
public int TimeoutSeconds { get; init; } = 15;
}Register Services in Program.cs
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddOptions<AzureOpenAIOptions>()
.Bind(builder.Configuration.GetSection(AzureOpenAIOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddOptions<OrderApiOptions>()
.Bind(builder.Configuration.GetSection(OrderApiOptions.SectionName))
.ValidateOnStart();
builder.Services.AddSingleton(sp =>
{
var options = sp.GetRequiredService<IOptions<AzureOpenAIOptions>>().Value;
return new AzureOpenAIClient(options.Endpoint, new DefaultAzureCredential());
});
builder.Services.AddHttpClient<IOrderApiClient, OrderApiClient>((sp, client) =>
{
var options = sp.GetRequiredService<IOptions<OrderApiOptions>>().Value;
client.BaseAddress = options.BaseUrl;
client.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);
}).AddStandardResilienceHandler();
builder.Services.AddScoped<ToolDispatcher>();
builder.Services.AddScoped<OrderSupportAgent>();
var app = builder.Build();
if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Implement the REST API Client
Keep downstream API integration in a typed client. This isolates HTTP concerns, simplifies testing, and prevents agent orchestration code from handling raw URLs or credentials.
public sealed record OrderDto(
string OrderId,
string CustomerId,
DateTimeOffset CreatedAt,
decimal Total,
string Currency);
public sealed record ShipmentStatusDto(
string OrderId,
string Status,
DateTimeOffset? EstimatedDelivery);
public interface IOrderApiClient
{
Task<OrderDto?> GetLatestOrderAsync(
string customerId, CancellationToken cancellationToken);
Task<ShipmentStatusDto?> GetShipmentStatusAsync(
string orderId, CancellationToken cancellationToken);
}using System.Net;
using System.Net.Http.Json;
public sealed class OrderApiClient(HttpClient httpClient) : IOrderApiClient
{
public async Task<OrderDto?> GetLatestOrderAsync(
string customerId, CancellationToken cancellationToken)
{
var encoded = Uri.EscapeDataString(customerId);
using var response = await httpClient.GetAsync(
$"api/customers/{encoded}/orders/latest", cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<OrderDto>(
cancellationToken: cancellationToken);
}
public async Task<ShipmentStatusDto?> GetShipmentStatusAsync(
string orderId, CancellationToken cancellationToken)
{
var encoded = Uri.EscapeDataString(orderId);
using var response = await httpClient.GetAsync(
$"api/orders/{encoded}/shipment", cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<ShipmentStatusDto>(
cancellationToken: cancellationToken);
}
}REST API Reliability Rules
Set explicit connection and request timeouts.
Retry only transient failures such as HTTP 408, 429, and selected 5xx responses.
Do not automatically retry non-idempotent POST, PATCH, or DELETE operations unless the API supports idempotency keys.
Apply circuit breaking and concurrency limits for unstable downstream systems.
Log status codes, duration, correlation IDs, and sanitized error details.
Never log tokens, full prompts containing confidential data, or unrestricted response bodies.
Define Tools and Dispatch Calls
Tool definitions should be small, deterministic, and aligned with business operations. Use clear descriptions because the model uses them to decide when each tool applies.
Tool | Inputs | Output | Risk level |
|---|---|---|---|
get_latest_order | customerId | Latest order summary | Read-only |
get_shipment_status | orderId | Shipment state and delivery estimate | Read-only |
create_support_ticket | orderId, reason | Ticket identifier | Write, approval may be required |
Tool Dispatcher
using System.Text.Json;
public sealed class ToolDispatcher(IOrderApiClient orderApi)
{
public async Task<string> ExecuteAsync(
string toolName,
string argumentsJson,
CancellationToken cancellationToken)
{
return toolName switch
{
"get_latest_order" => await GetLatestOrderAsync(
argumentsJson, cancellationToken),
"get_shipment_status" => await GetShipmentStatusAsync(
argumentsJson, cancellationToken),
_ => throw new InvalidOperationException(
$"Tool '{toolName}' is not registered.")
};
}
private async Task<string> GetLatestOrderAsync(
string json, CancellationToken cancellationToken)
{
var args = JsonSerializer.Deserialize<GetLatestOrderArgs>(json)
?? throw new ArgumentException("Invalid tool arguments.");
if (string.IsNullOrWhiteSpace(args.CustomerId) || args.CustomerId.Length > 50)
throw new ArgumentException("customerId is required and must be 50 characters or fewer.");
var result = await orderApi.GetLatestOrderAsync(
args.CustomerId, cancellationToken);
return JsonSerializer.Serialize(result ?? new { found = false });
}
private async Task<string> GetShipmentStatusAsync(
string json, CancellationToken cancellationToken)
{
var args = JsonSerializer.Deserialize<GetShipmentStatusArgs>(json)
?? throw new ArgumentException("Invalid tool arguments.");
if (string.IsNullOrWhiteSpace(args.OrderId) || args.OrderId.Length > 50)
throw new ArgumentException("orderId is required and must be 50 characters or fewer.");
var result = await orderApi.GetShipmentStatusAsync(
args.OrderId, cancellationToken);
return JsonSerializer.Serialize(result ?? new { found = false });
}
private sealed record GetLatestOrderArgs(string CustomerId);
private sealed record GetShipmentStatusArgs(string OrderId);
}
Join the conversation! Your thoughts help the community grow.