, ,

How to Use ChatGPT API in C# .NET 10

Chat GPT API in C# .NET 10
sharepointcafe Avatar

Artificial Intelligence is no longer a future concept—it is something developers use every day. One of the most powerful AI tools available today is ChatGPT. With the OpenAI API, you can integrate ChatGPT directly into your .NET applications.

In this article, you will learn how to consume the ChatGPT API using C# 14 and .NET 10, using top-level statements. The explanation is simple, practical, and beginner-friendly.

What we will build?

By the end of this article, you will have:

  • A working .NET 10 console application
  • Clean C# 14 code
  • Direct interaction with ChatGPT using HTTP
  • A structure that is easy to understand and extend

Using ChatGPT in a .NET application allows you to:

  • Automate responses to user questions
  • Generate text content dynamically
  • Explain code or technical topics
  • Summarize large amounts of text
  • Assist users in real time

Prerequisites

Before you start, make sure you have:

  • Visual Studio 2026
  • .NET 10 SDK installed
  • A valid OpenAI API key

Step 1: Create a New Console Project

Open Visual Studio and create a Console App project.

Select:

  • Framework: .NET 10
  • Language: C#

Step 2: Store the API Key Securely

Never hard-code your API key.

Create a file named appsettings.json and add:

{
  "OpenAI": {
    "ApiKey": "YOUR_OPENAI_API_KEY"
  }
}

Step 3: Write the Program Using Top-Level Statements

This file handles user input and prints the ChatGPT response.

Program.cs

using Microsoft.Extensions.Configuration;

Console.WriteLine("Hello, World!");

// Load configuration
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false)
    .Build();

string apiKey = config["OpenAI:ApiKey"]
    ?? throw new InvalidOperationException("OpenAI API key is missing.");

var openAiClient = new ChatGPT.ChatGPTClient(apiKey);

Console.Write("Ask ChatGPT: ");
string prompt = Console.ReadLine() ?? string.Empty;

if (string.IsNullOrWhiteSpace(prompt))
{
    Console.WriteLine("Prompt cannot be empty.");
    return;
}

string response = await openAiClient.GetChatResponseAsync(prompt);

Console.WriteLine("\nChatGPT Response:\n");
Console.WriteLine(response);

Step 4: Create the ChatGPT Client

This class is responsible for calling the OpenAI API.

ChatGPTClient.cs

using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace ChatGPT
{
    public class ChatGPTClient
    {
        private readonly HttpClient _httpClient;

        public ChatGPTClient(string apiKey)
        {
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://api.openai.com/v1/")
            };

            _httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", apiKey);
        }

        public async Task<string> GetChatResponseAsync(string userPrompt)
        {
            var request = new ChatCompletionRequest
            {
                Model = "gpt-4.1-mini",
                Messages =
                [
                    new ChatMessage("system", "You are a helpful assistant."),
                new ChatMessage("user", userPrompt)
                ]
            };

            using var content = new StringContent(
                JsonSerializer.Serialize(request),
                Encoding.UTF8,
                "application/json");

            using var response = await _httpClient.PostAsync("chat/completions", content);
            response.EnsureSuccessStatusCode();

            string json = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<ChatCompletionResponse>(json)!;

            return result.Choices[0].Message.Content;
        }
    }
}

Step 5: Define Request and Response Models

These models map the JSON request and response.

Models.cs

using System.Text.Json.Serialization;

public sealed class ChatCompletionRequest
{
    [JsonPropertyName("model")]
    public string Model { get; set; } = string.Empty;

    [JsonPropertyName("messages")]
    public List<ChatMessage> Messages { get; set; } = [];
}

public sealed class ChatMessage
{
    public ChatMessage(string role, string content)
    {
        Role = role;
        Content = content;
    }

    [JsonPropertyName("role")]
    public string Role { get; set; }

    [JsonPropertyName("content")]
    public string Content { get; set; }
}

public sealed class ChatCompletionResponse
{
    [JsonPropertyName("choices")]
    public List<Choice> Choices { get; set; } = [];
}

public sealed class Choice
{
    [JsonPropertyName("message")]
    public ChatMessage Message { get; set; } = default!;
}

Step 6: Run the Application

Run the project and type a question:

chat gpt api response output

Final Thoughts

ChatGPT brings powerful AI capabilities to .NET applications with very little effort. By using .NET 10, C# 14, you can create a modern, readable, and maintainable solution. This approach works well for learning projects, internal tools, and even production systems.

Keep Following: SharePointCafe.NET

Tagged in :

sharepointcafe Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *

RSS
YouTube
YouTube
Instagram