Merhaba arkadaşlar, bu yazımda .NET Core’da GraphQL ile Veri Kaydetme: Ürün Ekleme Örneği konusundan bahsedeceğim. Bir önceki yazımda Ürün Listelemesi gerçekleşmiştik. Aynı API üzerinden bu yazı içerisinde de Ürün Ekleme işlemi sağlayacağız. Bir ürünün detaylarını içeren bir GraphQL sorgusu (“mutation”) oluşturup, bunu API’ye göndermeyi ve API’den gelen cevabı işleyeceğiz.
Adım 1: Veri Modelini Tanımlama
API’ye göndereceğimiz ürün detaylarını temsil etmek için bir Product
sınıfı tanımlıyoruz. Bu sınıf, JSON serileştirme için JsonPropertyName
özelliğini kullanıyor.
public class Product
{
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("price")]
public decimal Price { get; set; }
[JsonPropertyName("description")]
public string? Description { get; set; }
[JsonPropertyName("category")]
public string? Category { get; set; }
[JsonPropertyName("stock")]
public int Stock { get; set; }
}
Ayrıca API’den gelen cevabın yapısını karşılamak için şu ek sınıfları tanımlıyoruz:
public class ProductResponse<T>
{
[JsonPropertyName("data")]
public T Data { get; set; }
}
public class ProductAddData
{
[JsonPropertyName("addProduct")]
public Product Product { get; set; }
}
Adım 2: GraphQL Mutation Tanımlama
GraphQL’de yeni bir kayıt oluşturmak için mutation
sorguları kullanılır. Aşağıdaki sorgu, yeni bir ürün eklemek için gerekli alanları ve parametreleri belirtmektedir:
string query = @"mutation AddProduct($product: ProductInput!) {
addProduct(product: $product) {
id,
category,
description,
name,
price,
stock
}
}";
Adım 3: Veri Gönderme ve Cevabı Alma
Bir Product
nesnesi oluşturuyor ve bu nesneyi JSON formatında GraphQL API’sine gönderiyoruz:
Product p1 = new Product
{
Name = "TEST",
Price = 10,
Description = "Description",
Category = "Category",
Stock = 10
};
var variables = new
{
product = new
{
name = p1.Name,
price = p1.Price,
description = p1.Description,
category = p1.Category,
stock = p1.Stock
}
};
string jsonQuery = JsonSerializer.Serialize(new { query, variables });
API ile iletişim için HttpClient
kullanıyoruz. Gelen cevabı işlemek için aşağıdaki kod örneği ile işlemleri gerçekleştirebilirsiniz.
using (var httpClient = new HttpClient())
{
try
{
var content = new StringContent(jsonQuery, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(apiUrl, content);
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
var productResponse = JsonSerializer.Deserialize<ProductResponse<ProductAddData>>(responseString);
if (productResponse != null)
{
var product = productResponse.Data.Product;
Console.WriteLine(product.Name);
}
else
{
Console.WriteLine("Product is not found!");
}
}
else
{
Console.WriteLine($"Hata: {response.StatusCode}");
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
catch (Exception ex)
{
Console.WriteLine($"Hata: {ex.Message}");
}
}
Adım 4: Sonuç
Bu blog yazısında, GraphQL kullanarak bir API’ye yeni bir ürün eklemeyi nasıl gerçekleştirebileceğinizi gördük.
Öne Çıkanlar:
- GraphQL sorgularını (“mutation”) .NET Core ile API’ye gönderme.
- Gelen cevabı serileştirme ve işleme.
Bir sonraki yazımda da yazdığımız kodları düzenleyerek daha okunabilir ve temiz bir hale getireceğiz.