How to Build a Gemini Chat API in ASP.NET Core 9 (Step-by-Step Guide)
![]() |
Vivek Jaiswal |
615 |
{{e.like}} |
{{e.dislike}} |
Introduction:
Want to integrate Google’s Gemini AI into your .NET app? In this tutorial, we’ll walk you through creating a Chat API using ASP.NET Core 9 and Gemini 2.0 from Google AI Studio — perfect for beginners!
๐ What You Will Learn
- What is Google Gemini API
- How to generate your Gemini API Key
- Building a Chat API in ASP.NET Core 9
- Full working source code with explanation
- Best practices for error handling & deployment
๐ง What is Gemini API?
Gemini is Google’s advanced multimodal AI model that you can access via Google AI Studio or Vertex AI. It allows you to send text prompts and receive smart, conversational responses. In this article, we are using the Gemini 2.0 Flash Model via Google AI Studio.
๐ Step 1: Get Your Gemini API Key
- Go to Google AI Studio
- Click on Create API Key
- Copy the key (keep it safe)
You’ll also see this testable curl code:
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent" \
-H "Content-Type: application/json" \
-H "X-goog-api-key: YOUR_API_KEY" \
-d '{"contents":[{"parts":[{"text":"Hello Gemini"}]}]}'
๐ Step 2: Create a New ASP.NET Core 9 Project
dotnet new webapi -n ChatApi
cd ChatApi
Install required packages:
dotnet add package Microsoft.AspNetCore.OpenApi
๐ Project Structure
ChatApi/
โโโ Controllers/
โ โโโ ChatController.cs
โโโ Models/
โ โโโ ChatRequest.cs
โ โโโ ChatResponse.cs
โโโ Services/
โ โโโ GeminiService.cs
โโโ Program.cs
๐ Models/ChatRequest.cs
This model represents the input data sent by the user. It only contains a single property Prompt, which is the text question or message you want to send to the Gemini API.
namespace ChatApi.Models;
public class ChatRequest
{
public string Prompt { get; set; }
}
๐ Models/ChatResponse.cs
This model represents the response that the Gemini API will return to the client. It wraps the output text in a simple Response property.
namespace ChatApi.Models;
public class ChatResponse
{
public string Response { get; set; }
}
๐ Services/GeminiService.cs
This service is the core of the application. It handles communication with the Gemini API using HttpClient. Here’s how it works:
- Builds a POST request with the user’s prompt.
- Sends it to the Gemini endpoint with your API key in headers.
- Parses the response JSON to extract the generated text.
- Returns the AI-generated text as a string.
using System.Text;
using System.Text.Json;
using ChatApi.Models;
namespace ChatApi.Services;
public class GeminiService
{
private readonly HttpClient _httpClient;
private readonly string _apiKey = "YOUR_GEMINI_API_KEY";
public GeminiService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetChatResponseAsync(string prompt)
{
var requestBody = new
{
contents = new[]
{
new {
parts = new[] {
new { text = prompt }
}
}
}
};
var request = new HttpRequestMessage(
HttpMethod.Post,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent");
request.Headers.Add("X-Goog-Api-Key", _apiKey);
request.Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
throw new Exception($"Gemini API Error: {response.StatusCode} - {error}");
}
using var responseStream = await response.Content.ReadAsStreamAsync();
using var doc = await JsonDocument.ParseAsync(responseStream);
var text = doc.RootElement
.GetProperty("candidates")[0]
.GetProperty("content")
.GetProperty("parts")[0]
.GetProperty("text")
.GetString();
return text ?? "No response from Gemini";
}
}
๐ Controllers/ChatController.cs
The controller exposes an HTTP POST endpoint /api/chat that clients can call with a prompt. It:
- Accepts a ChatRequest object from the request body.
- Passes the prompt to the GeminiService.
- Wraps the response and sends it back as a ChatResponse.
This abstraction keeps your business logic out of the controller.
using Microsoft.AspNetCore.Mvc;
using ChatApi.Models;
using ChatApi.Services;
namespace ChatApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
private readonly GeminiService _geminiService;
public ChatController(GeminiService geminiService)
{
_geminiService = geminiService;
}
[HttpPost]
public async Task<IActionResult> Chat([FromBody] ChatRequest request)
{
if (string.IsNullOrWhiteSpace(request.Prompt))
return BadRequest("Prompt is required.");
var response = await _geminiService.GetChatResponseAsync(request.Prompt);
return Ok(new ChatResponse { Response = response });
}
}
๐ Program.cs
The Program.cs file wires everything together:
- Registers GeminiService with dependency injection.
- Enables Swagger for API testing.
- Maps the controller endpoints.
using ChatApi.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpClient<GeminiService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
๐ Testing the API
Use Postman or Swagger to test the endpoint:
POST /api/chat
{
"prompt": "What is the capital of France?"
}
Response:
{
"response": "The capital of France is Paris."
}
๐ก Best Practices
- ๐ Store API keys securely in environment variables or user secrets.
- ๐งช Add logging for debugging API errors.
- ๐ Use caching to reduce latency if needed.
- ๐งต For advanced: Stream Gemini responses in real-time with SignalR or gRPC.
๐ Conclusion
With just a few lines of code, you’ve integrated Google Gemini into your own .NET app using ASP.NET Core 9! This API can be the foundation of AI-powered chatbots, assistants, content generators, and more.
๐ If you liked this tutorial, Share w,ith your friends for more .NET, AI, and backend development content!
Happy Coding! ๐ปโจ
Comments
![]() |
|
Follow up comments |
{{e.Name}} {{e.Comments}} |
{{e.days}} | |
|
||
|
{{r.Name}} {{r.Comments}} |
{{r.days}} | |
|