Why Use OpenAI with .NET 9?
.NET 9 brings Native AOT, built-in OpenAPI, and minimal APIs that fit AI-first apps perfectly. Combined with OpenAI’s API, you can add:
Conversational AI (ChatGPT)
Embeddings for semantic search
Image generation (DALL·E)
Structured JSON outputs for agents
Streaming responses for chatbots
This article shows you how to build production-ready integrations.
Getting Started with OpenAI in .NET 9
1. Install Packages
You can use the official OpenAI .NET SDK or raw HttpClient.
dotnet add package OpenAI
If you prefer HttpClient (no SDK dependency):
dotnet add package Microsoft.Extensions.Http
2. Add API Key to Configuration
appsettings.json:
{
"OpenAI": {
"ApiKey": "YOUR_API_KEY_HERE"
}
}
Or environment variable:
setx OPENAI_API_KEY "sk-xxxx"
3. Register OpenAI Client in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient("OpenAI", client =>
{
client.BaseAddress = new Uri("https://api.openai.com/v1/");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {builder.Configuration["OpenAI:ApiKey"]}");
});
var app = builder.Build();
Example 1: ChatGPT in Minimal API
app.MapPost("/chat", async (HttpClientFactory httpFactory, ChatRequest request) =>
{
var client = httpFactory.CreateClient("OpenAI");
var payload = new
{
model = "gpt-4o-mini",
messages = new[]
{
new { role = "system", content = "You are a helpful assistant." },
new { role = "user", content = request.Message }
}
};
var response = await client.PostAsJsonAsync("chat/completions", payload);
var result = await response.Content.ReadFromJsonAsync<ChatResponse>();
return Results.Ok(result?.Choices.FirstOrDefault()?.Message?.Content);
});
record ChatRequest(string Message);
record ChatResponse(List<Choice> Choices);
record Choice(Message Message);
record Message(string Role, string Content);
Test with:
curl -X POST https://localhost:5001/chat -H "Content-Type: application/json" -d "{ \"message\": \"Tell me about .NET 9\" }"
Example 2: Embeddings for Search
app.MapPost("/embed", async (HttpClientFactory httpFactory, TextRequest req) =>
{
var client = httpFactory.CreateClient("OpenAI");
var payload = new
{
model = "text-embedding-3-small",
input = req.Text
};
var response = await client.PostAsJsonAsync("embeddings", payload);
var result = await response.Content.ReadFromJsonAsync<EmbedResponse>();
return Results.Ok(result?.Data.FirstOrDefault()?.Embedding);
});
record TextRequest(string Text);
record EmbedResponse(List<EmbedData> Data);
record EmbedData(List<float> Embedding);

Join the conversation! Your thoughts help the community grow.