π Introduction
Generative AI APIs, such as OpenAI GPT, Azure OpenAI, Hugging Face, and Google Gemini, have transformed software development. These APIs allow developers to generate text, code, documentation, test cases, and even database queries dynamically β all from within their C# applications.
In this article, weβll explore how to use Generative AI APIs in C#, including setup, coding examples, and real-world use cases.
π§ What Is a Generative API?
A Generative API is a cloud-based service that takes input text (a prompt) and produces meaningful output such as code, summaries, or responses.
Common providers:
OpenAI API (ChatGPT, GPT-4, GPT-4o, etc.)
Azure OpenAI Service
Google Gemini API
Hugging Face Inference API
βοΈ Prerequisites
Before starting, ensure you have:
Visual Studio 2022 or VS Code
.NET 6 or higher
An API key from OpenAI, Azure OpenAI, or any other provider
π» Example 1: Using OpenAI GPT API in C#
This example demonstrates how to connect your C# app to the OpenAI GPT API to generate responses programmatically.
Step 1. Install NuGet Package
Open the Package Manager Console and install:
Install-Package OpenAI_API
Step 2. Write the C# Code
using System;
using System.Threading.Tasks;
using OpenAI_API;
namespace GenerativeAIExample
{
class Program
{
static async Task Main(string[] args)
{
// Your API key
string apiKey = "sk-your-openai-key";
// Initialize API
var api = new OpenAIAPI(apiKey);
// Prompt
Console.Write("Enter your prompt: ");
string prompt = Console.ReadLine();
// Generate completion
var result = await api.Completions.GetCompletion(prompt);
Console.WriteLine("\nAI Response:");
Console.WriteLine(result);
}
}
}
Output Example
Enter your prompt: Write a function to reverse a string in C#
AI Response:
public string ReverseString(string input)
{
char[] arr = input.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
π§© Example 2: Using Generative API for Code Generation
You can use the API to generate C#, SQL, or JavaScript code snippets dynamically β helpful for developers automating code creation or documentation.
string prompt = "Generate a SQL query to fetch all employees with salary > 50000";
var result = await api.Completions.GetCompletion(prompt);
Console.WriteLine("Generated Query: " + result);
β
Output
SELECT * FROM Employees WHERE Salary > 50000;
π§ͺ Example 3: Generative API for Unit Test Creation
AI can even create test cases automatically for existing functions.
string prompt = "Write NUnit test cases for a C# function that adds two numbers.";
var result = await api.Completions.GetCompletion(prompt);
Console.WriteLine(result);
β
Output
[TestFixture]
public class CalculatorTests
{
[Test]
public void Add_TwoNumbers_ReturnsSum()
{
var result = Calculator.Add(2, 3);
Assert.AreEqual(5, result);
}
}
π Example 4: Using Azure OpenAI API in C#
If youβre using Azure OpenAI, use HttpClient
for REST calls:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class AzureOpenAIExample
{
private static readonly string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/";
private static readonly string apiKey = "YOUR_AZURE_API_KEY";
public static async Task Main()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("api-key", apiKey);
var body = new
{
prompt = "Write C# code to sort an array using bubble sort.",
max_tokens = 150
};
var content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"{endpoint}openai/deployments/text-davinci-003/completions?api-version=2023-05-15", content);
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
π Real-World Use Cases
Use Case | Description |
---|
Code Assistant | Generate functions, SQL queries, and documentation |
Testing Automation | Generate unit test cases dynamically |
Chatbot Development | Build smart chat interfaces with AI |
Content Generation | Write blogs, summaries, and ad copies |
Error Explanation | Input exception messages, get human-readable explanations |
π Benefits for Developers
β
Speeds up development time
β
Reduces manual repetitive coding
β
Boosts code quality & documentation
β
Helps in prototyping and brainstorming ideas
π External References
π§Ύ Conclusion
Generative APIs are reshaping software development by enabling AI-assisted coding, automation, and innovation.
By integrating these APIs into your C# applications, you can build intelligent systems that generate, understand, and enhance code β bringing the power of AI directly into your development workflow.