GraphQL APIs with Spring Boot · Ders

Değişiklikler için Girdi Türlerinden Yararlanma

Daha temiz ve düzenli API çağrıları için yeniden kullanılabilir girdi türleri tanımlayarak değişiklik bağımsız değişkenlerini yalınlaştırın.

3. ders / 411 adım

Değişiklikler için Girdi Türlerinden Yararlanma, CoddyKit'te ücretsiz bir GraphQL APIs with Spring Boot dersidir. Bu, 4 dersinin 3. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, GraphQL APIs with Spring Boot öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. GraphQL APIs with Spring Boot kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Long Mutation Arguments?

When building GraphQL mutations, you often need to pass several pieces of data to create or update an entity. Think about creating a new user or a product.

Passing each field as a separate argument can make your mutation signatures quite long and hard to manage, leading to less readable and maintainable code.

Meet GraphQL Input Types

Input types are special object types in GraphQL used specifically as arguments for mutations (or sometimes queries). They allow you to group related fields into a single, structured object.

This makes your mutation definitions cleaner and more organized, similar to how a DTO (Data Transfer Object) works in traditional REST APIs.

Input Type Syntax (SDL)

Defining an input type in your GraphQL Schema Definition Language (SDL) is straightforward. You use the input keyword instead of type.

Input types can only contain scalar types, enums, or other input types as their fields. They cannot contain output object types, interfaces, or union types.

input CreateProductInput {
  name: String!
  description: String
  price: Float!
  category: String
}

The Problem: Many Arguments

Consider a mutation to create a new product. Without an input type, you might define it like this:

Notice how the argument list can become long and repetitive, especially if you have many fields. This can be cumbersome to write and read.

type Mutation {
  createProduct(
    name: String!,
    description: String,
    price: Float!,
    category: String
  ): Product
}

The Solution: Clean Mutations

By using our CreateProductInput, the mutation signature becomes much cleaner and easier to read. All related input fields are now encapsulated within a single argument.

This improves clarity and reduces clutter in your schema.

type Mutation {
  createProduct(input: CreateProductInput!): Product
}

input CreateProductInput {
  name: String!
  description: String
  price: Float!
  category: String
}

Spring Boot DTO for Input

In your Spring Boot application, you'll represent your GraphQL input types as simple Java classes. These act as Data Transfer Objects (DTOs) that Spring's GraphQL integration can automatically map for you.

Ensure the field names in your Java class match your SDL input type for seamless mapping.

package com.coddykit.graphql;

public class CreateProductInput {
    private String name;
    private String description;
    private float price;
    private String category;

    // Getters and Setters (omitted for brevity)
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    // ... other getters/setters
}

Using Input in Resolver

Now, let's see how your GraphQL resolver method in Spring Boot will use this CreateProductInput DTO. Instead of multiple @Argument annotations, you'll have just one for your input object.

This makes the resolver method signature much cleaner and easier to manage, especially with many input fields.

package com.coddykit.graphql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.stereotype.Controller;

// Dummy Product class for example return type
class Product {
    String id; String name; public Product(String id, String name) { this.id = id; this.name = name; } 
    public String getId() { return id; } public String getName() { return name; }
}

// Input DTO from previous scene
class CreateProductInput {
    private String name; private String description; private float price; private String category;
    public String getName() { return name; } public void setName(String name) { this.name = name; }
    public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
    public float getPrice() { return price; } public void setPrice(float price) { this.price = price; }
    public String getCategory() { return category; } public void setCategory(String category) { this.category = category; }
}

@SpringBootApplication
@Controller
public class Main {

    public static void main(String[] args) {
        // This would start a Spring Boot web server
        // SpringApplication.run(Main.class, args);
        System.out.println("Application context started (conceptually).");
    }

    private static long productIdCounter = 1;

    @MutationMapping
    public Product createProduct(@Argument CreateProductInput input) {
        System.out.println("Creating product: " + input.getName());
        // In a real application, you'd save this to a database
        String newId = "prod-" + productIdCounter++;
        return new Product(newId, input.getName());
    }
}

Why Use Input Types?

Input types offer several significant advantages for your GraphQL API design:

  • Readability: Mutation signatures become much shorter and clearer.
  • Reusability: The same input type can often be used for both creation and update mutations, reducing schema duplication.
  • Validation: It's easier to apply validation logic to a single, consolidated input object.
  • Extensibility: Adding new optional fields to an input type doesn't break existing clients, as they can simply ignore the new fields.

Complex Data with Nested Inputs

Input types can also contain other input types, allowing you to model complex, hierarchical data for your mutations. This is very powerful for structured data submission.

For example, when creating an order, you might need to include customer details and a list of items, each with its own properties, all within a single input object.

input AddressInput {
  street: String!
  city: String!
  zipCode: String
}

input CustomerInput {
  name: String!
  email: String!
  shippingAddress: AddressInput
}

input CreateOrderInput {
  customer: CustomerInput!
  items: [OrderItemInput!]!
}

input OrderItemInput {
  productId: ID!
  quantity: Int!
}

Input Types Check

You've learned about GraphQL Input Types and their benefits. Let's test your understanding!

Recap: Input Types Mastered!

Great job! In this lesson, you mastered GraphQL Input Types. You learned how they streamline mutation arguments, making your API cleaner and more maintainable.

  • We saw how to define input types in SDL using the input keyword.
  • Implemented them in Spring Boot resolvers by using DTOs.
  • And explored their key benefits like improved readability, reusability, and easier validation.

These are essential for building robust and user-friendly GraphQL APIs! Keep practicing!

Başlamak ücretsiz

Yapay zeka eğitmeniyle GraphQL APIs with Spring Boot öğren — ücretsiz

Tarayıcında gerçek kod yaz ve çalıştır, 7/24 yapay zeka eğitmeninden anında yardım al; web'de ya da uygulamada kaldığın yerden devam et.

Kurslar
12
Dersler
48

Sıkça Sorulan Sorular

“Değişiklikler için Girdi Türlerinden Yararlanma” dersi ücretsiz mi?

Evet — “Değişiklikler için Girdi Türlerinden Yararlanma” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve GraphQL APIs with Spring Boot kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. GraphQL APIs with Spring Boot kursu toplamda 4 dersten oluşur.

“Değişiklikler için Girdi Türlerinden Yararlanma” dersinde ne öğreneceğim?

Daha temiz ve düzenli API çağrıları için yeniden kullanılabilir girdi türleri tanımlayarak değişiklik bağımsız değişkenlerini yalınlaştırın. GraphQL APIs with Spring Boot ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

GraphQL APIs with Spring Boot öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te GraphQL APIs with Spring Boot, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 3. dersidir.

“Değişiklikler için Girdi Türlerinden Yararlanma” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu GraphQL APIs with Spring Boot dersinde kod yazıp çalıştırabilir miyim?

Evet. Her GraphQL APIs with Spring Boot dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. İç İçe Nesneleri ve İlişkileri Modelleme
  2. Arayüzleri ve Birleşim Türlerini Uygulama
  3. Değişiklikler için Girdi Türlerinden Yararlanma
  4. Numaralandırmalar ve Özel Skaler Türler
← GraphQL APIs with Spring Boot Sayfasına Dön