Integrating with the ChatGPT API

Consume OpenAI APIs from your C# app

Posted by Rodrigo Castro on January 4, 2025

You can call the OpenAI (ChatGPT) API using HttpClient in C#.

🔑 Get Your API Key

  • Sign up at OpenAI and create a key.

🚀 Sample POST Request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Net.Http;
using System.Text;
using System.Text.Json;

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_API_KEY");

var requestBody = new
{
    model = "gpt-3.5-turbo",
    messages = new[]
    {
        new { role = "user", content = "Hello, ChatGPT!" }
    }
};

var content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);

string responseJson = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseJson);

📝 Tips

  • Replace YOUR_API_KEY with your actual key.
  • Use System.Text.Json or Newtonsoft.Json to parse the response.

Next: Making API calls with HttpClient!