Lists and NonNull in GraphQL Schema (original) (raw)

Last Updated : 28 Apr, 2025

GraphQL is a powerful **open-source **Query Language for APIs. In 2012 it was first developed by a team of developers in Facebook and then it was later made public to the general people by making it open-source. Now it is being maintained by the GraphQL community.

GraphQL is most commonly known for its **single endpoint query which allows the user to define a single endpoint to fetch all the information needed. The benefit of using single endpoint queries is that they help the user in **reducing fetching too much data or less amount of data than required.

Lists and Non-Null

Lists and Non-Null are two important **data types in GraphQL that are used to define **GraphQL Schema. They are useful in defining the structure and constraints of data returned by GraphQL queries. Lists make the query fetching easier by helping the user to fetch the sequence of values required. Non-null constraints on a field help the users **prevent errors in the code while fetching the data.

**Prerequisites:

Below are the prerequisites that we need to install before executing the GraphQL query on our laptop or desktop.

Lists in GraphQL Schema

1. Nullable Lists

**Syntax :

type Query{
listName : [ dataType ], //Nullable List
}

2. Non-Nullable Lists

**Syntax :

type Query{
listName : [ dataType] ! //Non-nullable List
}

Example for Lists

In the below example, create a GraphQL schema to define a list of users.

**Step 1: Define the Schema

Let's create a schema and save the file as schema.graphql.

type Query {
users: [User]! #Non-Null List - User
}

type User {
userID: ID! #Non-Null field - userID
userName: String
userEmail: String
}

**Step 2: Implement Resolvers

Let's set up the server, save the file as server.js and we will implement resolvers for the users list.

JavaScript ``

const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const fs = require('fs'); const path = require('path');

const schema = buildSchema(fs.readFileSync(path.join(__dirname, 'schema.graphql'), 'utf8'));

const users = [ { userID: '1001', userName: 'User1', userEmail: 'user1@gmail.com' }, { userID: '1002', userName: 'User2', userEmail: 'user2@gmail.com' }, ];

const root = { users: () => users, };

const app = express();

app.use( '/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, }) );

const PORT = process.env.PORT || 4000; app.listen(PORT, () => { console.log(GraphQL server is running on http://localhost:${PORT}/graphql); });

``

**Step 3: Test Your List in GraphiQL

Run your GraphQL server.

node server.js

**Output:

list01

**Step 4: Execute the Below Query in the GraphiQL Interface

{
users {
userID
userName
userEmail
}
}

**Output:

We will receive a response with the list of users

userOP1

List of users

Passing Null Values

If we pass null value for users list like the below code we will get an error like "Cannot return null for non-nullable field Query.users"

usersNULL

Pass users list as null

**Output:

userListNull

Error when users list is passed as null

When a non-null field userID is not passed we will get an error like "Cannot return null for non-nullable field User.userID."

userIDnull

UserID is not passed

**Output:

usersOP2

Error when non-null field userID is not passed

Non-Null in GraphQL Schema

Why do We Need Non-Null?

The use of non-null fields in GraphQL is essential for a few reasons:

**Syntax:

fieldName : dataType! //Non-null Field

Example for Non-Null Field

In this example, we will create a GraphQL schema to define a list of persons with name of the person as null.

**Step 1: **Define a Non-Null Field in Your Schema

Let's create a schema and save the file as schema.graphql.

type Query {
person: [Person]
}

type Person {
name: String! # Non-Null field
age: Int
}

In this example, name is a non-null field. This implies that every person must have name when the query is executed.

**Step 2: **Implement Resolvers

Let's set up the server, save the file as server.js and we will implement resolvers for the name field.

JavaScript ``

const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const fs = require('fs'); const path = require('path');

const schema = buildSchema(fs.readFileSync(path.join(__dirname, 'schema.graphql'), 'utf8'));

const person = [ { name: 'Person1', age:22 }, { name: null, age:25 }, //name is a non-null field but passed as null ];

const root = { person: () => person, };

const app = express();

app.use( '/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, }) );

const PORT = process.env.PORT || 4000; app.listen(PORT, () => { console.log(GraphQL server is running on http://localhost:${PORT}/graphql); });

``

**Step 3: Test Your List in GraphiQL

Run your GraphQL server.

node server.js

non_null01

**Step 4: Execute the Below Query in the GraphiQL Interface

query {
person {
name
age
}
}

**Output:

So we will receive a response with the list of persons with the below error because we have passed the name of the person as null.

Here person name is a non-null field so it will not allow null value.

nonNullPerson

Error due to null passed in Non-null field

Handling the Non-Null Errors

const person = [ { name: 'Person1', age:22 }, { name: 'Person2', age:25 }, ];

`

correctCodePerson

Name of the person with non-null value

**Output:

person-valid-non-null

Output of Person without error

Conclusion

Lists and non-null constraints are crucial elements in GraphQL schema definition. Lists represent arrays or collections of values, and they can be either nullable or non-nullable. Non-null constraints ensure that certain fields always have a value, contributing to data integrity and making the API more predictable for users.