0Pricing
GraphQL APIs with Spring Boot · Урок

Проверка входных аргументов мутаций

Научитесь проверять входящие аргументы мутаций в API GraphQL на Spring Boot с помощью Bean Validation, чтобы до слоя данных доходили только корректные и хорошо сформированные данные.

«Проверка входных аргументов мутаций» — бесплатный урок GraphQL APIs with Spring Boot на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения GraphQL APIs with Spring Boot, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Validate Mutation Input?

Mutations change your data, so the arguments they receive must be trustworthy. Without validation, clients could send empty names, negative prices, or malformed emails straight into your database.

Input validation rejects bad data early and returns a clear error before any persistence happens.

Validation in the GraphQL Lifecycle

GraphQL already validates the shape of your input against the schema (types, required fields). But it does not check business rules like 'price must be positive'.

That semantic layer is your responsibility, and Spring's Bean Validation fits perfectly here.

Bean Validation Annotations

Spring Boot ships with Jakarta Bean Validation. Common annotations:

  • @NotNull, @NotBlank for required values
  • @Size for length bounds
  • @Min, @Max, @Positive for numbers
  • @Email for email format

Annotating an Input Class

Map your GraphQL input type to a Java record or class and add constraints to its fields.

public record CreateBookInput(
    @NotBlank String title,
    @Size(min = 2, max = 60) String author,
    @Positive double price
) {}

Triggering Validation in a Resolver

Add @Valid to the argument in your mutation method. Spring then checks every constraint before the method body runs.

@MutationMapping
public Book createBook(@Argument @Valid CreateBookInput input) {
    return bookService.create(input);
}

What Happens on Failure

If a constraint fails, Spring throws a ConstraintViolationException before your service code runs. The mutation does not persist anything, protecting your data layer from invalid state.

Custom Error Messages

Each annotation accepts a message attribute so clients see helpful feedback instead of a generic failure.

@NotBlank(message = "Title is required")
String title;

Mapping Violations to GraphQL Errors

Use a DataFetcherExceptionResolver to turn validation exceptions into clean GraphQL errors with field-level detail, so clients know exactly which input was wrong.

@Override
public GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) {
    return GraphqlErrorBuilder.newError(env)
        .errorType(ErrorType.BAD_REQUEST)
        .message(ex.getMessage())
        .build();
}

Custom Validators

For rules the built-in annotations cannot express (like 'ISBN must be unique'), write a custom constraint implementing ConstraintValidator and annotate fields with it.

public class IsbnValidator implements ConstraintValidator<ValidIsbn, String> {
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        return value != null && value.matches("\\d{13}");
    }
}

Validating Nested Inputs

When an input contains another object, mark the nested field with @Valid too. Validation then cascades into the child object.

public record OrderInput(
    @NotNull @Valid AddressInput shippingAddress,
    @Positive int quantity
) {}

Best Practices

Keep validation reliable:

  • Validate at the boundary, before any business logic
  • Return field-specific messages clients can act on
  • Reuse input classes across related mutations
  • Keep custom validators stateless and fast

Quick Check

Test your understanding of mutation validation.

Recap

You learned to validate mutation input:

  • GraphQL checks shape; you enforce business rules
  • Annotate input classes with Bean Validation constraints
  • Use @Valid in resolvers to trigger checks
  • Map violations to clean GraphQL errors
  • Write custom validators and cascade with nested @Valid

Validated mutations keep your data layer safe and clean.

Часто задаваемые вопросы

Урок «Проверка входных аргументов мутаций» бесплатный?

Да — полный текст урока «Проверка входных аргументов мутаций» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс GraphQL APIs with Spring Boot, подпишись на CoddyKit PRO. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Чему я научусь в уроке «Проверка входных аргументов мутаций»?

Научитесь проверять входящие аргументы мутаций в API GraphQL на Spring Boot с помощью Bean Validation, чтобы до слоя данных доходили только корректные и хорошо сформированные данные. Ты практикуешь GraphQL APIs with Spring Boot с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать GraphQL APIs with Spring Boot?

Предыдущий опыт не требуется. GraphQL APIs with Spring Boot на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Проверка входных аргументов мутаций»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке GraphQL APIs with Spring Boot?

Да. Каждый урок GraphQL APIs with Spring Boot включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Понимание мутаций GraphQL
  2. Создание данных с помощью мутаций
  3. Обновление и удаление данных
  4. Проверка входных аргументов мутаций
← Назад к GraphQL APIs with Spring Boot