Basics

GraphQL Data Types

GraphQL Data Types

GraphQL data types include Int String and custom objects.

Introduction to GraphQL Data Types

GraphQL is a query language for APIs that allows you to request exactly the data you need. To ensure type safety and clarity, GraphQL uses specific data types. In this guide, we'll explore the fundamental GraphQL data types, including scalars like Int and String, as well as custom object types.

Scalar Types: Int and String

Scalar types are the basic data types of GraphQL. They represent a single value and are akin to primitive types in other programming languages. The most common scalar types are:

  • Int - Represents a signed 32‐bit integer.
  • String - Represents textual data, encoded as UTF‐8 character sequences.

These types are used to define fields in your GraphQL schema and ensure the data returned matches these expectations.

Custom Object Types

Beyond scalar types, GraphQL allows you to define custom object types to represent more complex data structures. These types are composed of multiple fields, each with a specific type, which can be scalars or other object types.

Here's how you can define a custom object type:

In this example, the User type is an object type with three fields: id, name, and age, each with their respective scalar types.

Object types allow you to structure your API's data model in a way that closely resembles real-world entities.

Using GraphQL Types in Queries

Once you have defined your types, you can use them in queries to request specific data. For example, you can query the User type to fetch user details:

This query requests the id, name, and age fields of the User type, demonstrating how GraphQL's type system ensures that the data structure is both predictable and flexible.

Conclusion

Understanding GraphQL data types is crucial for defining a robust API schema. By leveraging scalar and custom object types, you can create a clear, concise, and efficient API that meets your application's data needs. In the next post, we'll delve into Operators and how they interact with GraphQL types.

Previous
Variables