Validare gli argomenti di input delle mutation
Impari a validare gli argomenti in ingresso delle mutation in un'API GraphQL Spring Boot usando Bean Validation, assicurandosi che solo dati puliti e correttamente formati raggiungano il livello dati.
Validare gli argomenti di input delle mutation è una lezione GraphQL APIs with Spring Boot gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento GraphQL APIs with Spring Boot, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso GraphQL APIs with Spring Boot include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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,@NotBlankfor required values@Sizefor length bounds@Min,@Max,@Positivefor numbers@Emailfor 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
@Validin 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.
Impara GraphQL APIs with Spring Boot con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Validare gli argomenti di input delle mutation» è gratuita?
Sì — il testo completo di «Validare gli argomenti di input delle mutation» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso GraphQL APIs with Spring Boot, passa a CoddyKit PRO. Il corso GraphQL APIs with Spring Boot include 4 lezioni in totale.
Cosa imparerò in «Validare gli argomenti di input delle mutation»?
Impari a validare gli argomenti in ingresso delle mutation in un'API GraphQL Spring Boot usando Bean Validation, assicurandosi che solo dati puliti e correttamente formati raggiungano il livello dati. Eserciti GraphQL APIs with Spring Boot con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare GraphQL APIs with Spring Boot?
Non è richiesta alcuna esperienza precedente. GraphQL APIs with Spring Boot su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Validare gli argomenti di input delle mutation»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione GraphQL APIs with Spring Boot?
Sì. Ogni lezione GraphQL APIs with Spring Boot include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Comprendere le mutation GraphQL
- Creare dati con le mutation
- Aggiornare ed eliminare dati
- Validare gli argomenti di input delle mutation