0Pricing
GraphQL APIs with Spring Boot · Leçon

Énumérations et types scalaires personnalisés

Étendez votre schéma GraphQL au-delà des types intégrés en définissant des énumérations pour les ensembles de valeurs fixes et des scalaires personnalisés pour les types métier tels que les dates et les URL dans Spring Boot.

Énumérations et types scalaires personnalisés est une leçon GraphQL APIs with Spring Boot gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage GraphQL APIs with Spring Boot, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours GraphQL APIs with Spring Boot comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Beyond Built-in Types

GraphQL ships with scalars like Int, String, and Boolean. But real domains need more: a fixed set of statuses, a proper date type, or a validated email.

Enums and custom scalars let your schema express these precisely.

What Is a GraphQL Enum?

An enum restricts a field to a fixed list of named values. Clients can only send or receive one of those values, and tooling can offer autocompletion.

enum OrderStatus {
  PENDING
  SHIPPED
  DELIVERED
  CANCELLED
}

Using an Enum in a Type

Reference the enum like any other type. The field is now guaranteed to hold a valid status.

type Order {
  id: ID!
  status: OrderStatus!
}

Mapping Enums to Java

Spring for GraphQL maps a schema enum to a Java enum automatically when the names match exactly.

public enum OrderStatus {
    PENDING, SHIPPED, DELIVERED, CANCELLED
}

Why Custom Scalars?

The built-in scalars are limited. Representing a date as a String loses meaning and validation. A custom scalar defines how a domain value is serialized, deserialized, and validated.

Declaring a Scalar in the Schema

First declare the scalar name in your SDL, then use it on fields.

scalar DateTime

type Event {
  id: ID!
  startsAt: DateTime!
}

Using a Pre-built Scalar Library

The graphql-java-extended-scalars library provides ready-made scalars for DateTime, Date, URL, and more, so you do not write them by hand.

// build.gradle
implementation 'com.graphql-java:graphql-java-extended-scalars:21.0'

Registering a Scalar in Spring

Wire the scalar into the runtime with a RuntimeWiringConfigurer bean so the schema knows how to handle it.

@Bean
public RuntimeWiringConfigurer scalars() {
    return wiring -> wiring.scalar(ExtendedScalars.DateTime);
}

Writing Your Own Scalar

For a domain type you can define a GraphQLScalarType with a custom Coercing implementation controlling parse and serialize logic.

GraphQLScalarType.newScalar()
    .name("Email")
    .coercing(new EmailCoercing())
    .build();

Validation Inside Coercing

A scalar's Coercing can reject invalid input by throwing a CoercingParseValueException, giving you type-level validation for free.

if (!value.toString().contains("@")) {
    throw new CoercingParseValueException("Invalid email");
}

Best Practices

Use these types wisely:

  • Prefer enums over free-form strings for fixed sets
  • Reuse library scalars before writing your own
  • Keep Coercing logic pure and predictable
  • Document each custom scalar's expected format

Quick Check

Test your knowledge of enums and scalars.

Recap

You extended your schema's type system:

  • Enums restrict fields to a fixed value set
  • They map automatically to Java enums by name
  • Custom scalars model domain types like dates and emails
  • Use library scalars or write a Coercing for your own
  • Register scalars via RuntimeWiringConfigurer

Richer types make your API safer and more expressive.

Questions Fréquemment Posées

La leçon « Énumérations et types scalaires personnalisés » est-elle gratuite ?

Oui — le texte complet de « Énumérations et types scalaires personnalisés » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours GraphQL APIs with Spring Boot, passe à CoddyKit PRO. Le cours GraphQL APIs with Spring Boot comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Énumérations et types scalaires personnalisés » ?

Étendez votre schéma GraphQL au-delà des types intégrés en définissant des énumérations pour les ensembles de valeurs fixes et des scalaires personnalisés pour les types métier tels que les dates et… Tu pratiques GraphQL APIs with Spring Boot avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer GraphQL APIs with Spring Boot ?

Aucune expérience préalable n'est requise. GraphQL APIs with Spring Boot sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.

Combien de temps prend la leçon « Énumérations et types scalaires personnalisés » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon GraphQL APIs with Spring Boot ?

Oui. Chaque leçon GraphQL APIs with Spring Boot inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Modéliser les objets imbriqués et les relations
  2. Implémenter les interfaces et les types union
  3. Exploiter les types d'entrée pour les mutations
  4. Énumérations et types scalaires personnalisés
← Retour à GraphQL APIs with Spring Boot