Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL spec List and NonNull clarification

Tags:

graphql

I'm having some trouble interpreting this part of the GraphQL spec.

https://facebook.github.io/graphql/#sec-Combining-List-and-Non-Null

1.

If the modified type of a List is Non‐Null, then that List may not contain any null items.

2.

If the modified type of a Non‐Null is List, then null is not accepted, however an empty list is accepted.

I'm assuming the representation of these are

  1. List[Type!]
  2. List[Type]!

Assuming this much is correct.

First question: For 1, the spec doesn't explicitly say empty lists are invalid, should it?

This test in the graphql-js project suggests it should not.

if so, there is nothing in the spec to specify non-empty lists?

Second question: Without the modifier (1) should I be able to submit a List with null values (like below)?

List[Book]

Book
title: String!

createBook(input: {books: [{null, {title: "Book a"}}]})

GraphiQL does not seem to allow adding null to a list regardless of whether the modifier is present or not. Would that be a bug in GraphiQL?

like image 345
andrewe Avatar asked Feb 18 '26 18:02

andrewe


1 Answers

You assume correctly. There are four possible combinations:

[String]

null // valid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // valid

[String!]

null // valid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // invalid

[String]!

null // invalid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // valid

[String!]!

null // invalid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // invalid

First question: For 1, the spec doesn't explicitly say empty lists are invalid, should it?

It doesn't have to. By default all types in GraphQL can be nullable, lists included. The first example above applies.

Second question: Without the modifier (1) should I be able to submit a List with null values (like below)?

Yes. The GraphQL spec section 5.3.3 states that arguments have to be compatible with the type defined in the schema.

In practice however, it is useless to send a list with null elements. This might be why GraphiQL doesn't go for it.


Side note: Regarding when to use non-nullable types or not, this article can add some perspective on why having nullable types in your GraphQL API can be a good choice even if the field shouldn't be null.

like image 176
Ire Avatar answered Feb 21 '26 15:02

Ire