Definición de tipos de datos personalizados
Cree tipos de objeto, tipos escalares y enumeraciones personalizados en su esquema de GraphQL para representar los datos de su aplicación.
Definición de tipos de datos personalizados es una lección gratuita de GraphQL APIs with Spring Boot en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de GraphQL APIs with Spring Boot, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de GraphQL APIs with Spring Boot incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Custom Types: Your Data's Blueprint
In GraphQL, data types are like blueprints for your application's information. They define the shape and kind of data that can be queried or modified.
While GraphQL provides some basic types, you'll often need to define your own to perfectly match your application's unique data structure.
GraphQL's Building Blocks
GraphQL has built-in scalar types like String, Int, Boolean, Float, and ID. These are fundamental, single-value types.
But real-world data is complex! This is where Object Types come in. They let you define objects with multiple fields, each having its own type.
Crafting Object Types
You define an object type using the type keyword in GraphQL's Schema Definition Language (SDL). Think of it as creating a custom class or struct.
Each field within an object type has a name and a type. Fields can be other object types, scalar types, or even lists of types.
Example: A 'Book' Object
Let's imagine we're building an API for a library. We'd need a way to represent a book. Here's how you might define a Book object type:
type Book {
id: ID!
title: String!
author: String
publicationYear: Int
}The ! after a type means the field is non-nullable – it must always have a value.
Beyond Basic Scalars
Sometimes, built-in scalars aren't specific enough. For example, a Date field could be a String, but what if you need to ensure a specific format?
Custom Scalar Types allow you to define your own scalar types with specific serialization, parsing, and validation rules. This ensures data consistency.
Declaring Custom Scalars
Defining a custom scalar in your schema is straightforward. You use the scalar keyword, followed by the name of your new scalar type.
Later, your Spring Boot application will need to provide the actual logic for handling this custom scalar's data transformations.
scalar Date
type Event {
id: ID!
name: String!
eventDate: Date!
}Enums for Fixed Values
Enum Types (short for 'enumeration') are special scalar types that represent a finite set of possible values. They're great for fields where you want to restrict choices to a predefined list.
Using enums makes your schema more self-documenting and helps prevent invalid data from being sent to your API.
Defining an Enum Type
For our library API, a book might have a specific status. We can define an enum for this:
enum BookStatus {
AVAILABLE
CHECKED_OUT
LOST
REPAIR
}Now, any field using BookStatus can only have one of these four values.
Combining Your Custom Types
Let's update our Book type to use our new BookStatus enum and a custom Date scalar.
scalar Date
enum BookStatus {
AVAILABLE
CHECKED_OUT
LOST
}
type Book {
id: ID!
title: String!
author: String
publicationYear: Int
status: BookStatus!
lastCheckedOut: Date
}This shows how custom types build a richer, more precise schema.
Check Your Understanding
Which of the following statements about GraphQL custom data types are TRUE?
Recap: Your Data's Foundation
You've learned how to define custom data types in GraphQL using SDL!
- Object Types (
type) structure complex data. - Custom Scalar Types (
scalar) handle specific data formats. - Enum Types (
enum) restrict field values to a finite set.
These tools are crucial for building a precise and robust GraphQL schema that accurately represents your application's domain.
Preguntas frecuentes
¿La lección «Definición de tipos de datos personalizados» es gratis?
Sí — el texto completo de «Definición de tipos de datos personalizados» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de GraphQL APIs with Spring Boot, actualiza a CoddyKit PRO. El curso de GraphQL APIs with Spring Boot incluye 4 lecciones en total.
¿Qué aprenderé en «Definición de tipos de datos personalizados»?
Cree tipos de objeto, tipos escalares y enumeraciones personalizados en su esquema de GraphQL para representar los datos de su aplicación. Practicas GraphQL APIs with Spring Boot con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar GraphQL APIs with Spring Boot?
No se requiere experiencia previa. GraphQL APIs with Spring Boot en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Definición de tipos de datos personalizados»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de GraphQL APIs with Spring Boot?
Sí. Cada lección de GraphQL APIs with Spring Boot incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Definición de tipos de datos personalizados
- Implementación de resolvers de datos
- Ejecución de consultas sencillas de GraphQL
- Mutaciones de GraphQL: modificación de datos