<labelid="sidebar-toggle"class="icon-button"for="sidebar-toggle-anchor"title="Toggle Table of Contents"aria-label="Toggle Table of Contents"aria-controls="sidebar">
<ahref="print.html"title="Print this book"aria-label="Print this book">
<iid="print-button"class="fa fa-print"></i>
</a>
</div>
</div>
<divid="search-wrapper"class="hidden">
<formid="searchbar-outer"class="searchbar-outer">
<inputtype="search"id="searchbar"name="searchbar"placeholder="Search this book ..."aria-controls="searchresults-outer"aria-describedby="searchresults-header">
<p><ahref="https://graphql.org">GraphQL</a> is a query language for APIs and a runtime for fulfilling those queries with your existing data. <ahref="https://graphql.org">GraphQL</a> provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.</p>
</blockquote>
<p><ahref="https://docs.rs/juniper">Juniper</a> is a library for creating <ahref="https://graphql.org">GraphQL</a> servers in <ahref="https://www.rust-lang.org">Rust</a>. Build type-safe and fast API servers with minimal boilerplate and configuration (we do try to make declaring and resolving <ahref="https://graphql.org">GraphQL</a> schemas as convenient as possible as <ahref="https://www.rust-lang.org">Rust</a> will allow).</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> doesn't include a web server itself, instead, it provides building blocks to make integration with existing web servers straightforward. It optionally provides a pre-built integration for some widely used web server frameworks in <ahref="https://www.rust-lang.org">Rust</a> ecosystem.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> supports the full GraphQL query language according to the <ahref="https://spec.graphql.org/October2021">specification (October 2021)</a>.</p>
<blockquote>
<p><strong>NOTE</strong>: As an exception to other <ahref="https://graphql.org">GraphQL</a> libraries for other languages, <ahref="https://docs.rs/juniper">Juniper</a> builds non-<code>null</code> types by default. A field of type <code>Vec<Episode></code> will be converted into <code>[Episode!]!</code>. The corresponding Rust type for a <code>null</code>able <code>[Episode]</code> would be <code>Option<Vec<Option<Episode>>></code> instead.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> provides out-of-the-box integration for some very common <ahref="https://www.rust-lang.org">Rust</a> crates to make building schemas a breeze. The types from these crates will be usable in your schemas automatically after enabling the correspondent self-titled <ahref="https://doc.rust-lang.org/cargo/reference/features.html">Cargo feature</a>:</p>
<p>This page will give you a short introduction to the concepts in <ahref="https://docs.rs/juniper">Juniper</a>.</p>
<p><strong><ahref="https://docs.rs/juniper">Juniper</a> follows a <ahref="https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#code-only">code-first</a> approach to define a <ahref="https://graphql.org">GraphQL</a> schema.</strong></p>
<blockquote>
<p><strong>TIP</strong>: For a <ahref="https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#schema-first">schema-first</a> approach, consider using a <ahref="https://docs.rs/juniper-from-schema"><code>juniper-from-schema</code></a> crate for generating a <ahref="https://docs.rs/juniper"><code>juniper</code></a>-based code from a <ahref="https://graphql.org/learn/schema">schema</a> file.</p>
<p>Exposing simple enums and structs as <ahref="https://graphql.org">GraphQL</a> types is just a matter of adding a custom <ahref="https://doc.rust-lang.org/stable/reference/attributes/derive.html#derive">derive attribute</a> to them. <ahref="https://docs.rs/juniper">Juniper</a> includes support for basic <ahref="https://www.rust-lang.org">Rust</a> types that naturally map to <ahref="https://graphql.org">GraphQL</a> features, such as <code>Option<T></code>, <code>Vec<T></code>, <code>Box<T></code>, <code>Arc<T></code>, <code>String</code>, <code>f64</code>, <code>i32</code>, references, slices and arrays.</p>
<p>For more advanced mappings, <ahref="https://docs.rs/juniper">Juniper</a> provides multiple macros to map your <ahref="https://www.rust-lang.org">Rust</a> types to a <ahref="https://graphql.org/learn/schema">GraphQL schema</a>. The most important one is the <ahref="https://docs.rs/juniper/0.16.0/juniper/macro.graphql_object.html"><code>#[graphql_object]</code> attribute</a> that is used for declaring a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> with resolvers (typically used for declaring <ahref="https://spec.graphql.org/October2021#sec-Root-Operation-Types"><code>Query</code> and <code>Mutation</code> roots</a>).</p>
<p>Now we have a very simple but functional schema for a <ahref="https://graphql.org">GraphQL</a> server!</p>
<p>To actually serve the <ahref="https://graphql.org/learn/schema">schema</a>, see the guides for our various <ahref="serve/index.html">server integrations</a>.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> is a library that can be used in many contexts: it doesn't require a server, nor it has a dependency on a particular transport or serialization format. You can invoke the <code>juniper::execute()</code> directly to get a result for a <ahref="https://graphql.org">GraphQL</a> query:</p>
<pre><preclass="playground"><codeclass="language-rust edition2021"><spanclass="boring">// Only needed due to 2018 edition because the macro is not accessible.
<p>Most of the work in working with <ahref="https://docs.rs/juniper">Juniper</a> consists of mapping the <ahref="https://spec.graphql.org/October2021#sec-Type-System">GraphQL type system</a> to the <ahref="https://www.rust-lang.org">Rust</a> types our application uses.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> provides some convenient abstractions making this process as painless as possible.</p>
<p>Find out more in the individual chapters below:</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL objects</a> represent a list of named fields, each of which yield a value of a specific type.</p>
</blockquote>
<p>When declaring a <ahref="https://graphql.org/learn/schema">GraphQL schema</a>, most of the time we deal with <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL objects</a>, because they are the only place where we actually define the behavior once <ahref="https://graphql.org/learn/schema">schema</a> gets <ahref="https://spec.graphql.org/October2021#sec-Execution">executed</a>.</p>
<p>There are two ways to define a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> in <ahref="https://docs.rs/juniper">Juniper</a>:</p>
<li>The easiest way, suitable for trivial cases, is to use the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLObject.html"><code>#[derive(GraphQLObject)]</code> attribute</a> on a <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a>, as described below.</li>
<li>The other way, using the <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_object.html"><code>#[graphql_object]</code> attribute</a>, is described in the <ahref="types/objects/complex_fields.html">"Complex fields" chapter</a>.</li>
<p>While any type in <ahref="https://www.rust-lang.org">Rust</a> can be exposed as a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>, the most common one is a <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a>:</p>
<p>This creates a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> type called <code>Person</code>, with two fields: <code>name</code> of type <code>String!</code>, and <code>age</code> of type <code>Int!</code>. Because of <ahref="https://www.rust-lang.org">Rust</a>'s type system, everything is exported as <ahref="https://spec.graphql.org/October2021#sec-Non-Null">non-<code>null</code></a> by default.</p>
<p><strong>TIP</strong>: If a <code>null</code>able field is required, the most obvious way is to use <code>Option</code>. Or <ahref="https://docs.rs/juniper/0.16.0/juniper/enum.Nullable.html"><code>Nullable</code></a> for distinguishing between <ahref="https://spec.graphql.org/October2021#sel-EAFdRDHAAEJDAoBxzT">explicit and implicit <code>null</code>s</a>.</p>
<p>We should take advantage of the fact that <ahref="https://graphql.org">GraphQL</a> is <ahref="https://spec.graphql.org/October2021#sec-Introspection">self-documenting</a> and add descriptions to the defined <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> type and its fields. <ahref="https://docs.rs/juniper">Juniper</a> will automatically use associated <ahref="https://doc.rust-lang.org/reference/comments.html#doc-comments">Rust doc comments</a> as <ahref="https://spec.graphql.org/October2021#sec-Descriptions">GraphQL descriptions</a>:</p>
<p>If using <ahref="https://doc.rust-lang.org/reference/comments.html#doc-comments">Rust doc comments</a> is not desired (for example, when we want to keep <ahref="https://www.rust-lang.org">Rust</a> API docs and GraphQL schema descriptions different), the <code>#[graphql(description = "...")]</code> attribute can be used instead, which takes precedence over <ahref="https://doc.rust-lang.org/reference/comments.html#doc-comments">Rust doc comments</a>:</p>
<p>By default, <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a> fields are converted from <ahref="https://www.rust-lang.org">Rust</a>'s standard <code>snake_case</code> naming convention into <ahref="https://graphql.org">GraphQL</a>'s <code>camelCase</code> convention:</p>
<p>To <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecate</a> a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> field, either the <code>#[graphql(deprecated = "...")]</code> attribute, or <ahref="https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute">Rust's <code>#[deprecated]</code> attribute</a>, should be used:</p>
<p><strong>NOTE</strong>: Only <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>/<ahref="https://spec.graphql.org/October2021#sec-Interfaces">interface</a> fields and <ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> values can be <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecated</a>.</p>
<p>By default, all <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a> fields are included into the generated <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> type. To prevent inclusion of a specific field annotate it with the <code>#[graphql(ignore)]</code> attribute:</p>
<p><strong>TIP</strong>: See more available features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLObject.html"><code>#[derive(GraphQLObject)]</code></a> attribute.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> fields can be of any <ahref="https://graphql.org">GraphQL</a> type, except <ahref="https://spec.graphql.org/October2021#sec-Input-Objects">input objects</a>.</p>
<p>Let's see what it means to build relationships between <ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a>:</p>
<p>Because <code>Person</code> is a valid <ahref="https://graphql.org">GraphQL</a> type, we can have a <code>Vec<Person></code> in a <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a>, and it'll be automatically converted into a <ahref="https://spec.graphql.org/October2021#sec-List">list</a> of <ahref="https://spec.graphql.org/October2021#sec-Non-Null">non-<code>null</code>able</a><code>Person</code><ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a>.</p>
<p>Using a plain <ahref="https://doc.rust-lang.org/reference/items/structs.html">Rust struct</a> for representing a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> is easy and trivial but does not cover every case. What if we need to express something non-trivial as a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL field</a>, such as:</p>
<ul>
<li>Calling non-trivial logic while <ahref="https://spec.graphql.org/October2021#sec-Execution">executing</a> the <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> (like querying database, etc.).</li>
<li>Defining a circular <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>, where one of its <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> returns the type itself.</li>
<li>Using some other (non-<ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a>) <ahref="https://www.rust-lang.org">Rust</a> type to represent a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>.</li>
<p>To support these more complicated use cases, we need a way to define a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL field</a> as a function. In <ahref="https://docs.rs/juniper">Juniper</a> this is achievable by placing the <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_object.html"><code>#[graphql_object]</code> attribute</a> on an <ahref="https://doc.rust-lang.org/reference/items/implementations.html#inherent-implementations"><code>impl</code> block</a>, which turns its methods into <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL fields</a>:</p>
<p><strong>NOTE</strong>: To access global data such as database connections or authentication information, a <em>context</em> is used. To learn more about this, see the <ahref="types/objects/context.html">"Context" chapter</a>.</p>
<p>Though <ahref="https://www.rust-lang.org">Rust</a> doesn't have the notion of default arguments, <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL arguments</a> are able to have default values. These default values are used when a GraphQL operation doesn't specify the argument explicitly. In <ahref="https://docs.rs/juniper">Juniper</a>, defining a default value for a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL argument</a> is enabled by the <code>#[graphql(default)]</code> attribute:</p>
<p>Like with the <ahref="types/objects/index.html#renaming"><code>#[derive(GraphQLObject)]</code> attribute on structs</a>, <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> names are converted from <ahref="https://www.rust-lang.org">Rust</a>'s standard <code>snake_case</code> naming convention into <ahref="https://graphql.org">GraphQL</a>'s <code>camelCase</code> convention.</p>
<p>We can override the name by using the <code>#[graphql(name = "...")]</code> attribute:</p>
<p><strong>TIP</strong>: Supported policies are: <code>SCREAMING_SNAKE_CASE</code>, <code>camelCase</code> and <code>none</code> (disables any renaming).</p>
</blockquote>
<h3id="documentation-and-deprecation"><aclass="header"href="#documentation-and-deprecation">Documentation and deprecation</a></h3>
<p>Similarly, <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL fields</a> may also be <ahref="https://spec.graphql.org/October2021#sec-Descriptions">documented</a> and <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecated</a> via <code>#[graphql(description = "...")]</code> and <code>#[graphql(deprecated = "...")]</code>/<ahref="https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute"><code>#[deprecated]</code></a> attributes:</p>
<p><strong>NOTE</strong>: Only <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>/<ahref="https://spec.graphql.org/October2021#sec-Interfaces">interface</a> fields and <ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> values can be <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecated</a>.</p>
<p>By default, all methods of an <ahref="https://doc.rust-lang.org/reference/items/implementations.html#inherent-implementations"><code>impl</code> block</a> are exposed as <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL fields</a>. If a method should not be exposed as a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL field</a>, it should be defined in a separate <ahref="https://doc.rust-lang.org/reference/items/implementations.html#inherent-implementations"><code>impl</code> block</a> or marked with the <code>#[graphql(ignore)]</code> attribute:</p>
<p><strong>TIP</strong>: See more available features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_object.html"><code>#[graphql_object]</code></a> attribute.</p>
<p><em>Context</em> is a feature in <ahref="https://docs.rs/juniper">Juniper</a> that lets <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> resolvers access global data, most commonly database connections or authentication information.</p>
<p>Let's say that we have a simple <code>User</code>s database in a <code>HashMap</code>:</p>
<p>We would like to define a <code>friends</code><ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> on <code>User</code> that returns a list of <code>User</code><ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a>. In order to write such a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> we need to query a <code>Database</code>. To accomplish this we must first mark the <code>Database</code> as a valid context type and then assign it to the <code>User</code><ahref="https://spec.graphql.org/October2021#sec-Objects">object</a>. To gain access to the context in the <code>friends</code><ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a>, we need to specify an argument with the same type as the specified context:</p>
<h3id="mutating-and-mutable-references"><aclass="header"href="#mutating-and-mutable-references">Mutating and mutable references</a></h3>
<p>Context cannot be a mutable reference as <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> may be resolved concurrently. If something in the context requires a mutable reference, the context type should leverage the <ahref="https://doc.rust-lang.org/reference/interior-mutability.html#interior-mutability"><em>interior mutability</em> pattern</a> (e.g. use <code>RwLock</code>, <code>RefCell</code> or similar).</p>
<p>For example, when using async runtime with <ahref="https://en.wikipedia.org/wiki/Work_stealing">work stealing</a> (like <ahref="https://docs.rs/tokio"><code>tokio</code></a>), which obviously requires thread safety in addition, we will need to use a corresponding async version of <code>RwLock</code>:</p>
<p><strong>TIP</strong>: Replace <code>tokio::sync::RwLock</code> with <code>std::sync::RwLock</code> (or similar) if you don't intend to use async resolving.</p>
<p>Error handling in <ahref="https://graphql.org">GraphQL</a> can be done in multiple ways. We will cover the two different error handling models mostly used:</p>
<ol>
<li><ahref="types/objects/error/field.html">Implicit field results</a>.</li>
<li><ahref="types/objects/error/schema.html">Explicit errors backend by GraphQL schema</a>.</li>
</ol>
<p>Choosing the right error handling method depends on the requirements of the application and the concrete error happening. Investigating both approaches is beneficial.</p>
<p>The <ahref="types/objects/error/field.html">first approach</a> (where every error is a <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">field error</a>) is easier to implement. However, clients won't know what errors may occur and instead will have to infer what happens from the <ahref="https://spec.graphql.org/October2021/#sel-GAPHRPDCAACCyD57Z">error message</a>. This is brittle and could change over time due to either clients or server changing. Therefore, extensive integration testing between clients and server is required to maintain the implicit contract between the two.</p>
<p><ahref="types/objects/error/schema.html">Encoding non-critical errors in a GraphQL schema</a> makes the contract between clients and the server explicit. This allows clients to understand and handle these errors correctly and the server to know when changes are potentially breaking clients. However, encoding this error information into a <ahref="https://graphql.org/learn/schema">GraphQL schema</a> requires additional code and up-front definition of non-critical errors.</p>
<p><ahref="https://www.rust-lang.org">Rust</a> provides <ahref="https://doc.rust-lang.org/book/ch09-00-error-handling.html">two ways of dealing with errors</a>:</p>
<ul>
<li><ahref="https://doc.rust-lang.org/stable/std/result/enum.Result.html"><code>Result<T, E></code></a> for recoverable errors;</li>
<li><ahref="https://doc.rust-lang.org/stable/std/macro.panic.html"><code>panic!</code></a> for unrecoverable errors.</li>
</ul>
<p><ahref="https://docs.rs/juniper">Juniper</a> does not do anything about panicking, it naturally bubbles up to the surrounding code/framework and can be dealt with there.</p>
<p>For recoverable errors, <ahref="https://docs.rs/juniper">Juniper</a> works well with the <ahref="https://doc.rust-lang.org/stable/std/result/enum.Result.html">built-in <code>Result</code> type</a>. You can use the <ahref="https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator"><code>?</code> operator</a> and things will work as you expect them to:</p>
<p><ahref="https://docs.rs/juniper/0.16.0/juniper/executor/type.FieldResult.html"><code>FieldResult<T></code></a> is an alias for <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.FieldError.html"><code>Result<T, FieldError></code></a>, which is the <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">error type</a> all fallible <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> must return. By using the <ahref="https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator"><code>?</code> operator</a>, any type that implements the <ahref="https://doc.rust-lang.org/stable/std/fmt/trait.Display.html"><code>Display</code> trait</a> (which most of the error types out there do) can be automatically converted into a <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.FieldError.html"><code>FieldError</code></a>.</p>
<p><strong>TIP</strong>: If a custom conversion into a <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.FieldError.html"><code>FieldError</code></a> is needed (to <ahref="https://spec.graphql.org/October2021#sel-GAPHRPZCAACCC_7Q">fill up <code>extensions</code></a>, for example), the <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/trait.IntoFieldError.html"><code>IntoFieldError</code> trait</a> should be implemented.</p>
<p><strong>NOTE</strong>: <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.FieldError.html"><code>FieldError</code></a>s are <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">GraphQL field errors</a> and are <ahref="https://spec.graphql.org/October2021#sec-Introspection">not visible</a> in a <ahref="https://graphql.org/learn/schema">GraphQL schema</a> in any way.</p>
<h2id="error-payloads-null-and-partial-errors"><aclass="header"href="#error-payloads-null-and-partial-errors">Error payloads, <code>null</code>, and partial errors</a></h2>
<p><ahref="https://docs.rs/juniper">Juniper</a>'s error behavior conforms to the <ahref="https://spec.graphql.org/October2021#sec-Handling-Field-Errors">GraphQL specification</a>.</p>
<p>When a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> returns an <ahref="https://doc.rust-lang.org/book/ch09-00-error-handling.html">error</a>, the <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a>'s result is replaced by <code>null</code>, and an additional <code>errors</code> object is created at the top level of the <ahref="https://spec.graphql.org/October2021#sec-Response">response</a>, and the <ahref="https://spec.graphql.org/October2021#sec-Execution">execution</a> is resumed.</p>
<p>Let's run the following query against the previous example:</p>
<pre><codeclass="language-graphql">{
example {
contents
foo
}
}
</code></pre>
<p>If <code>str::from_utf8</code> results in a <code>std::str::Utf8Error</code>, then the following will be returned:</p>
<pre><codeclass="language-json">{
"data": {
"example": {
"contents": "<Contents of the file>",
"foo": null
}
},
"errors": [{
"message": "invalid utf-8 sequence of 2 bytes from index 0",
"locations": [{"line": 2, "column": 4}]
}]
}
</code></pre>
<blockquote>
<p>Since <ahref="https://spec.graphql.org/October2021#sec-Non-Null"><code>Non-Null</code> type</a><ahref="https://spec.graphql.org/October2021#sec-Execution">fields</a> cannot be <strong>null</strong>, <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">field errors</a> are propagated to be handled by the parent <ahref="https://spec.graphql.org/October2021#sec-Execution">field</a>. If the parent <ahref="https://spec.graphql.org/October2021#sec-Execution">field</a> may be <strong>null</strong> then it resolves to <strong>null</strong>, otherwise if it is a <ahref="https://spec.graphql.org/October2021#sec-Non-Null"><code>Non-Null</code> type</a>, the <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">field error</a> is further propagated to its parent <ahref="https://spec.graphql.org/October2021#sec-Execution">field</a>.</p>
</blockquote>
<p>For example, with the following query:</p>
<pre><codeclass="language-graphql">{
example {
contents
}
}
</code></pre>
<p>If the <code>File::open()</code> above results in a <code>std::io::ErrorKind::PermissionDenied</code>, the following ill be returned:</p>
<p>Sometimes it's desirable to return additional structured error information to clients. This can be accomplished by implementing the <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/trait.IntoFieldError.html"><code>IntoFieldError</code> trait</a>:</p>
<p>And the specified structured error information will be included into the <ahref="https://spec.graphql.org/October2021#sel-GAPHRPZCAACCC_7Q">error's <code>extensions</code></a>:</p>
<pre><codeclass="language-json">{
"errors": [{
"message": "Whatever does not exist",
"locations": [{"line": 2, "column": 4}],
"extensions": {
"type": "NO_WHATEVER"
}
}]
}
</code></pre>
<blockquote>
<p><strong>NOTE</strong>: This pattern is particularly useful when it comes to instrumentation of returned <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">field errors</a> with custom error codes or additional diagnostics (like stack traces or tracing IDs).</p>
<p><ahref="https://www.rust-lang.org">Rust</a>'s model of errors can be adapted for <ahref="https://graphql.org">GraphQL</a>. <ahref="https://www.rust-lang.org">Rust</a>'s panic is similar to a <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">field error</a> - the whole query is aborted and nothing can be extracted (except for error related information).</p>
<p>Not all errors require this strict handling. Recoverable or partial errors can be put into a <ahref="https://graphql.org/learn/schema">GraphQL schema</a>, so the client can intelligently handle them.</p>
<p>To implement this approach, all errors must be partitioned into two classes:</p>
<ul>
<li><em>Critical</em> errors that cannot be fixed by clients (e.g. a database error).</li>
<li><em>Recoverable</em> errors that can be fixed by clients (e.g. invalid input data).</li>
</ul>
<p>Critical errors are returned from resolvers as <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">field errors</a> (from the <ahref="types/objects/error/field.html">previous chapter</a>). Recoverable errors are part of a <ahref="https://graphql.org/learn/schema">GraphQL schema</a> and can be handled gracefully by clients. Similar to <ahref="https://www.rust-lang.org">Rust</a>, <ahref="https://graphql.org">GraphQL</a> allows similar error models with <ahref="https://spec.graphql.org/October2021#sec-Unions">unions</a> (see <ahref="types/objects/error/../../unions.html">"Unions" chapter</a>).</p>
<p>In this example, basic input validation is implemented with <ahref="https://spec.graphql.org/October2021#sec-Types">GraphQL types</a>. <ahref="https://spec.graphql.org/October2021#sec-String">Strings</a> are used to identify the problematic <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> name. Errors for a particular <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> are also returned as a <ahref="https://spec.graphql.org/October2021#sec-String">string</a>.</p>
<p>Each function may have a different return type and depending on the input parameters a new result type may be required. For example, adding a <code>User</code> would require a new result type containing the variant <code>Ok(User)</code>instead of <code>Ok(Item)</code>.</p>
<blockquote>
<p><strong>NOTE</strong>: In this example the returned <ahref="https://spec.graphql.org/October2021#sec-String">string</a> contains a server-side localized error message. However, it is also
possible to return a unique string identifier and have the client present a localized string to its users.</p>
</blockquote>
<p>The client can send a mutation request and handle the resulting errors in the following manner:</p>
<pre><codeclass="language-graphql">{
mutation {
addItem(name: "", quantity: 0) {
... on Item {
name
}
... on ValidationErrors {
errors {
field
message
}
}
}
}
}
</code></pre>
<blockquote>
<p><strong>NOTE</strong>: A useful side effect of this approach is to have partially successful queries or mutations. If one resolver fails, the results of the successful resolvers are not discarded.</p>
<p>Instead of using <ahref="https://spec.graphql.org/October2021#sec-String">strings</a> to propagate errors, it is possible to use <ahref="https://spec.graphql.org/October2021#sec-Types">GraphQL type system</a> to describe the errors more precisely.</p>
<p>For each fallible <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">input argument</a> we create a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> in a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>. The <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> is set if the validation for that particular <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">argument</a> fails.</p>
<p><strong>NOTE</strong>: We will likely want some kind of code generation to reduce repetition as the number of types required is significantly larger than before. Each resolver function has a custom <code>ValidationResult</code> which contains only <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> provided by the function.</p>
</blockquote>
<p>So, all the expected errors are handled directly inside the query. Additionally, all non-critical errors are known in advance by both the server and the client:</p>
<pre><codeclass="language-graphql">{
mutation {
addItem {
... on Item {
name
}
... on ValidationErrorsItem {
name
quantity
}
}
}
}
</code></pre>
<h3id="example-complex-with-critical-errors"><aclass="header"href="#example-complex-with-critical-errors">Example: Complex with critical errors</a></h3>
<p>Our examples so far have only included non-critical errors. Providing errors inside a <ahref="https://graphql.org/learn/schema">GraphQL schema</a> still allows us to return unexpected critical errors when they occur.</p>
<p>In the following example, a theoretical database could fail and would generate errors. Since it is not common for a database to fail, the corresponding error is returned as a <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">critical error</a>:</p>
<p>The <ahref="https://shopify.dev/docs/admin-api/graphql/reference">Shopify API</a> implements a similar approach. Their API is a good reference to explore this approach in a real world application.</p>
<p>Up until now, we've only looked at mapping <ahref="https://doc.rust-lang.org/reference/items/structs.html">structs</a> to <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL objects</a>. However, any <ahref="https://www.rust-lang.org">Rust</a> type can be exposed a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>.</p>
<p>Using <code>Result</code>-like <ahref="https://spec.graphql.org/October2021#sec-Errors.Field-errors">enums</a> can be a useful way of reporting validation errors from a mutation:</p>
<p>Here, we use an <ahref="https://doc.rust-lang.org/reference/items/enumerations.html">enum</a> to decide whether a client's input data is valid or not, and it could be used as the result of e.g. a <code>signUp</code> mutation:</p>
<p>Yet another point where <ahref="https://graphql.org">GraphQL</a> and <ahref="https://www.rust-lang.org">Rust</a> differs is in how generics work:</p>
<ul>
<li>In <ahref="https://www.rust-lang.org">Rust</a>, almost any type could be generic - that is, take type parameters.</li>
<li>In <ahref="https://graphql.org">GraphQL</a>, there are only two generic types: <ahref="https://spec.graphql.org/October2021#sec-List">lists</a> and <ahref="https://spec.graphql.org/October2021#sec-Non-Null">non-<code>null</code>ables</a>.</li>
</ul>
<p>This poses a restriction on what we can expose in <ahref="https://graphql.org">GraphQL</a> from <ahref="https://www.rust-lang.org">Rust</a>: no generic structs can be exposed - all type parameters must be bound. For example, we cannot expose <code>Result<T, E></code> as a <ahref="https://spec.graphql.org/October2021#sec-Types">GraphQL type</a>, but we <em>can</em> expose <code>Result<User, String></code> as a <ahref="https://spec.graphql.org/October2021#sec-Types">GraphQL type</a>.</p>
<p>Let's make a slightly more compact but generic implementation of <ahref="types/objects/error/schema.html#example-non-struct-objects">the last schema error example</a>:</p>
<p>Here, we've made a wrapper around a <code>Result</code> and exposed some concrete instantiations of <code>Result<T, E></code> as distinct <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL objects</a>.</p>
<blockquote>
<p><strong>NOTE</strong>: The reason we needed the wrapper is of <ahref="https://www.rust-lang.org">Rust</a>'s <ahref="https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence">orphan rules</a> (both the <code>Result</code> and <ahref="https://docs.rs/juniper">Juniper</a>'s internal traits are from third-party sources).</p>
</blockquote>
<blockquote>
<p><strong>NOTE</strong>: Because we're using generics, we also need to specify a <code>name</code> for our instantiated <ahref="https://spec.graphql.org/October2021#sec-Types">GraphQL types</a>. Even if <ahref="https://docs.rs/juniper">Juniper</a><em>could</em> figure out the name, <code>MutationResult<User></code> wouldn't be a <ahref="https://spec.graphql.org/October2021#sec-Names">valid GraphQL type name</a>. And, also, two different <ahref="https://spec.graphql.org/October2021#sec-Types">GraphQL types</a> cannot have the same <code>MutationResult</code> name, inferred by default.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interfaces</a> represent a list of named <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> and their <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">arguments</a>. <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL objects</a> and <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> can then implement these <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> which requires that the implementing type will define all <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> defined by those <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a>.</p>
</blockquote>
<p><ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interfaces</a> map well to interfaces known from common object-oriented languages such as Java or C#, but <ahref="https://www.rust-lang.org">Rust</a>, unfortunately, has no concept that maps perfectly to them. The nearest analogue of <ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interfaces</a> are <ahref="https://doc.rust-lang.org/reference/items/traits.html#traits">Rust traits</a>, but the main difference is that in <ahref="https://graphql.org">GraphQL</a> an <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interface type</a> serves both as an <em>abstraction</em> and a <em>boxed value (dispatchable to concrete implementers)</em>, while in <ahref="https://www.rust-lang.org">Rust</a>, a <ahref="https://doc.rust-lang.org/reference/items/traits.html#traits">trait</a> is an <em>abstraction only</em>, and <em>to represent such a boxed value a separate type is required</em>, like a <ahref="https://doc.rust-lang.org/reference/types/trait-object.html#trait-objects">trait object</a> or an <ahref="https://doc.rust-lang.org/reference/items/enumerations.html#enumerations">enum</a> consisting of implementer types, because <ahref="https://doc.rust-lang.org/reference/items/traits.html#traits">Rust trait</a> doesn't represent a type itself, and so, can have no values.</p>
<p>Another notable difference is that <ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interfaces</a> are more like <ahref="https://en.wikipedia.org/wiki/Structural_type_system">structurally-typed</a> contracts: they <em>only declare a list of <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a></em> a <ahref="https://graphql.org">GraphQL</a> type should already have. <ahref="https://doc.rust-lang.org/reference/items/traits.html#traits">Rust traits</a>, on the other hand, are <ahref="https://en.wikipedia.org/wiki/Type_class">type classes</a>, which don't really care about existing methods, but, rather, <em>require to provide implementations for required methods</em> despite the fact whether the type already has such methods or not. This difference makes the <ahref="https://doc.rust-lang.org/reference/items/implementations.html#trait-implementations">trait implementation</a> not a good fit for expressing a <ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interface</a> implementation, because <em>we don't really need to implement any <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a></em>, the <ahref="https://graphql.org">GraphQL</a> type implementing a <ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interface</a> has those <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> already. <em>We only need to check that <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields'</a> signatures match</em>.</p>
<p>That's why <ahref="https://docs.rs/juniper">Juniper</a> takes the following approach to represent <ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interfaces</a>, which consists of two parts:</p>
<ol>
<li>Either a <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a>, or a <ahref="https://doc.rust-lang.org/reference/items/traits.html#traits">trait</a> (in case <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> have <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">arguments</a>), which acts only as a blueprint describing the required list of <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a>, and is not used in runtime at all.</li>
<li>An auto-generated <ahref="https://doc.rust-lang.org/reference/items/enumerations.html#enumerations">enum</a>, representing a dispatchable value-type for the <ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interfaces</a>, which may be referred and returned by other <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a>.</li>
<p>This may be done by using either the <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_interface.html"><code>#[graphql_interface]</code> attribute</a> or the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLInterface.html"><code>#[derive(GraphQLInterface)]</code></a>:</p>
<h3id="interfaces-implementing-other-interfaces"><aclass="header"href="#interfaces-implementing-other-interfaces">Interfaces implementing other interfaces</a></h3>
<p><ahref="https://graphql.org">GraphQL</a> allows implementing <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> on other <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> in addition to <ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a>:</p>
<p><strong>NOTE</strong>: Every <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interface</a> has to specify all other <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a>/<ahref="https://spec.graphql.org/October2021#sec-Interfaces">objects</a> it implements or implemented for. Missing one of <code>for = </code> or <code>impl = </code> attribute arguments is a <strong>compile-time error</strong>.</p>
<h3id="subtyping-and-additional-nullable-arguments"><aclass="header"href="#subtyping-and-additional-nullable-arguments">Subtyping and additional <code>null</code>able arguments</a></h3>
<p><ahref="https://graphql.org">GraphQL</a> allows implementers (both <ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a> and other <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a>) to return "subtypes" instead of an original value. Basically, this allows to impose additional bounds on the implementation.</p>
<p>Valid "subtypes" are:</p>
<ul>
<li><ahref="https://spec.graphql.org/October2021#sec-Interfaces">interface</a> implementer instead of an <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interface</a> itself:
<ul>
<li><code>I implements T</code> in place of a <code>T</code>;</li>
<li><code>Vec<I implements T></code> in place of a <code>Vec<T></code>.</li>
</ul>
</li>
<li><ahref="https://spec.graphql.org/October2021#sec-Non-Null">non-<code>null</code></a> value in place of a <code>null</code>able:
<ul>
<li><code>T</code> in place of a <code>Option<T></code>;</li>
<li><code>Vec<T></code> in place of a <code>Vec<Option<T>></code>.</li>
</ul>
</li>
</ul>
<p>These rules are recursively applied, so <code>Vec<Vec<I implements T>></code> is a valid "subtype" of a <code>Option<Vec<Option<Vec<Option<T>>>>></code>.</p>
<p>Also, <ahref="https://graphql.org">GraphQL</a> allows implementers to add <code>null</code>able <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">field arguments</a>, which aren't present on an original interface.</p>
<p><strong>NOTE</strong>: Violating <ahref="https://graphql.org">GraphQL</a> "subtyping" or additional <code>null</code>able <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">argument</a> rules is a <strong>compile-time error</strong>.</p>
<p><ahref="types/objects/complex_fields.html#default-arguments">Similarly to GraphQL object fields</a>, <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL arguments</a> of <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> are able to have default values, though <ahref="https://www.rust-lang.org">Rust</a> doesn't have such notion:</p>
<p>Just as with <ahref="types/objects/index.html#renaming">defining GraphQL objects</a>, by default, <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> are converted from <ahref="https://www.rust-lang.org">Rust</a>'s standard <code>snake_case</code> naming convention into <ahref="https://graphql.org">GraphQL</a>'s <code>camelCase</code> convention:</p>
<p>We can override the name by using the <code>#[graphql(name = "...")]</code> attribute:</p>
<p><strong>TIP</strong>: Supported policies are: <code>SCREAMING_SNAKE_CASE</code>, <code>camelCase</code> and <code>none</code> (disables any renaming).</p>
</blockquote>
<h3id="documentation-and-deprecation-1"><aclass="header"href="#documentation-and-deprecation-1">Documentation and deprecation</a></h3>
<p>Similarly, <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL fields</a> of <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> may also be <ahref="https://spec.graphql.org/October2021#sec-Descriptions">documented</a> and <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecated</a> via <code>#[graphql(description = "...")]</code> and <code>#[graphql(deprecated = "...")]</code>/<ahref="https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute"><code>#[deprecated]</code></a> attributes:</p>
<p><strong>NOTE</strong>: Only <ahref="https://spec.graphql.org/October2021#sec-Interfaces">GraphQL interface</a>/<ahref="https://spec.graphql.org/October2021#sec-Objects">object</a> fields and <ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> values can be <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecated</a>.</p>
<p>By default, all <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a> fields or <ahref="https://doc.rust-lang.org/reference/items/traits.html#traits">trait</a> methods are considered as <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">GraphQL fields</a>. If a helper method is needed, or it should be ignored for some reason, then it should be marked with the <code>#[graphql(ignore)]</code> attribute:</p>
<p><strong>TIP</strong>: See more available features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_interface.html"><code>#[graphql_interface]</code></a> attribute.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Unions">GraphQL unions</a> represent an object that could be one of a list of <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> types, but provides for no guaranteed fields between those types. They also differ from <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> in that <ahref="https://spec.graphql.org/October2021#sec-Objects">object</a> types declare what <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a> they implement, but are not aware of what <ahref="https://spec.graphql.org/October2021#sec-Unions">unions</a> contain them.</p>
</blockquote>
<p>From the server's point of view, <ahref="https://spec.graphql.org/October2021#sec-Unions">GraphQL unions</a> are somewhat similar to <ahref="https://spec.graphql.org/October2021#sec-Interfaces">interfaces</a>: the main difference is that they don't contain fields on their own, and so, we only need to represent a value, <em>dispatchable</em> into concrete <ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a>.</p>
<p>Obviously, the most straightforward approach to express <ahref="https://spec.graphql.org/October2021#sec-Unions">GraphQL unions</a> in <ahref="https://www.rust-lang.org">Rust</a> is to use <ahref="https://doc.rust-lang.org/reference/items/enumerations.html#enumerations">enums</a>. In <ahref="https://docs.rs/juniper">Juniper</a> this may be done by using <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLUnion.html"><code>#[derive(GraphQLInterface)]</code></a> attribute on them:</p>
<p>Just as with <ahref="types/objects/index.html#renaming">renaming GraphQL objects</a>, we can override the default <ahref="https://spec.graphql.org/October2021#sec-Unions">union</a> name by using the <code>#[graphql(name = "...")]</code> attribute:</p>
<p><strong>NOTE</strong>: Unlike <ahref="https://doc.rust-lang.org/reference/items/enumerations.html#enumerations">Rust enum variants</a>, <ahref="https://spec.graphql.org/October2021#sec-Unions">GraphQL union members</a> don't have any special names aside from the ones provided by <ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a> themselves, and so, obviously, <strong>cannot be renamed</strong>.</p>
<p>Similarly to <ahref="types/objects/index.html#documentation">documenting GraphQL objects</a>, we can <ahref="https://spec.graphql.org/October2021#sec-Descriptions">document</a> a <ahref="https://spec.graphql.org/October2021#sec-Unions">GraphQL union</a> via <code>#[graphql(description = "...")]</code> attribute or <ahref="https://doc.rust-lang.org/reference/comments.html#doc-comments">Rust doc comments</a>:</p>
<p><strong>NOTE</strong>: Unlike <ahref="https://doc.rust-lang.org/reference/items/enumerations.html#enumerations">Rust enum variants</a>, <ahref="https://spec.graphql.org/October2021#sec-Unions">GraphQL union members</a> don't have any special constructors aside from the provided <ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a> directly, and so, <strong>cannot be <ahref="https://spec.graphql.org/October2021#sec-Descriptions">documented</a></strong>, but rather reuse <ahref="https://spec.graphql.org/October2021#sec-Descriptions">object descriptions</a> "as is".</p>
<p>In some rare situations we may want to omit exposing an <ahref="https://doc.rust-lang.org/reference/items/enumerations.html#enumerations">enum</a> variant in a <ahref="https://graphql.org/learn/schema">GraphQL schema</a>. <ahref="types/enums.html#ignoring">Similarly to GraphQL enums</a>, we can just annotate the variant with the <code>#[graphql(ignore)]</code> attribute.</p>
<p>As an example, let's consider the situation where we need to bind some type parameter <code>T</code> for doing interesting type-level stuff in our resolvers. To achieve this we need to have <code>PhantomData<T></code>, but we don't want it exposed in the GraphQL schema.</p>
<p><strong>WARNING</strong>: It's the <em>library user's responsibility</em> to ensure that ignored <ahref="https://doc.rust-lang.org/reference/items/enumerations.html#enumerations">enum</a> variant is <strong>never</strong> returned from resolvers, otherwise resolving the <ahref="https://graphql.org">GraphQL</a> query will <strong>panic in runtime</strong>.</p>
<p><strong>TIP</strong>: See more available features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLUnion.html"><code>#[derive(GraphQLUnion)]</code></a> attribute.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> types, like <ahref="https://spec.graphql.org/October2021#sec-Scalars">scalar</a> types, also represent leaf values in a GraphQL type system. However <ahref="https://spec.graphql.org/October2021#sec-Enums">enum</a> types describe the set of possible values.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Enums">Enums</a> are not references for a numeric value, but are unique values in their own right. They may serialize as a string: the name of the represented value.</p>
<p>With <ahref="https://docs.rs/juniper">Juniper</a> a <ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> may be defined by using the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLEnum.html"><code>#[derive(GraphQLEnum)]</code></a> attribute on a <ahref="https://doc.rust-lang.org/reference/items/enumerations.html">Rust enum</a> as long as its variants do not have any fields:</p>
<p>By default, <ahref="https://doc.rust-lang.org/reference/items/enumerations.html">enum</a> variants are converted from <ahref="https://www.rust-lang.org">Rust</a>'s standard <code>PascalCase</code> naming convention into <ahref="https://graphql.org">GraphQL</a>'s <code>SCREAMING_SNAKE_CASE</code> convention:</p>
<p><strong>TIP</strong>: Supported policies are: <code>SCREAMING_SNAKE_CASE</code>, <code>camelCase</code> and <code>none</code> (disables any renaming).</p>
</blockquote>
<h3id="documentation-and-deprecation-2"><aclass="header"href="#documentation-and-deprecation-2">Documentation and deprecation</a></h3>
<p>Just like when <ahref="types/objects/index.html#documentation">defining GraphQL objects</a>, the <ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> type and its values could be <ahref="https://spec.graphql.org/October2021#sec-Descriptions">documented</a> and <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecated</a> via <code>#[graphql(description = "...")]</code> and <code>#[graphql(deprecated = "...")]</code>/<ahref="https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute"><code>#[deprecated]</code></a> attributes:</p>
<p><strong>NOTE</strong>: Only <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>/<ahref="https://spec.graphql.org/October2021#sec-Interfaces">interface</a> fields and <ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> values can be <ahref="https://spec.graphql.org/October2021#sec--deprecated">deprecated</a>.</p>
<p>By default, all <ahref="https://doc.rust-lang.org/reference/items/enumerations.html">enum</a> variants are included in the generated <ahref="https://spec.graphql.org/October2021#sec-Enums">GraphQL enum</a> type as values. To prevent including a specific variant, annotate it with the <code>#[graphql(ignore)]</code> attribute:</p>
<p><strong>TIP</strong>: See more available features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLEnum.html"><code>#[derive(GraphQLEnum)]</code></a> attribute.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Language.Fields">Fields</a> may accept <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">arguments</a> to configure their behavior. These inputs are often <ahref="https://spec.graphql.org/October2021#sec-Scalars">scalars</a> or <ahref="https://spec.graphql.org/October2021#sec-Enums">enums</a>, but they sometimes need to represent more complex values.</p>
<p>A <ahref="https://spec.graphql.org/October2021#sec-Input-Objects">GraphQL input object</a> defines a set of input fields; the input fields are either <ahref="https://spec.graphql.org/October2021#sec-Scalars">scalars</a>, <ahref="https://spec.graphql.org/October2021#sec-Enums">enums</a>, or other <ahref="https://spec.graphql.org/October2021#sec-Input-Objects">input objects</a>. This allows <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">arguments</a> to accept arbitrarily complex structs.</p>
<p>In <ahref="https://docs.rs/juniper">Juniper</a>, defining a <ahref="https://spec.graphql.org/October2021#sec-Input-Objects">GraphQL input object</a> is quite straightforward and similar to how <ahref="types/objects/index.html">trivial GraphQL objects are defined</a> - by using the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLInputObject.html"><code>#[derive(GraphQLInputObject)]</code> attribute</a> on a <ahref="https://doc.rust-lang.org/reference/items/structs.html">Rust struct</a>:</p>
<p>Just as with <ahref="types/objects/index.html#renaming">defining GraphQL objects</a>, by default <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a> fields are converted from <ahref="https://www.rust-lang.org">Rust</a>'s standard <code>snake_case</code> naming convention into <ahref="https://graphql.org">GraphQL</a>'s <code>camelCase</code> convention:</p>
<p>Similarly, <ahref="https://spec.graphql.org/October2021#sec-Descriptions">GraphQL descriptions</a> may be provided by either using <ahref="https://doc.rust-lang.org/reference/comments.html#doc-comments">Rust doc comments</a> or with the <code>#[graphql(description = "...")]</code> attribute:</p>
<p>By default, all <ahref="https://doc.rust-lang.org/reference/items/structs.html">struct</a> fields are included into the generated <ahref="https://spec.graphql.org/October2021#sec-Input-Objects">GraphQL input object</a> type. To prevent inclusion of a specific field annotate it with the <code>#[graphql(ignore)]</code> attribute:</p>
<blockquote>
<p><strong>WARNING</strong>: Ignored fields must either implement <code>Default</code> or be annotated with the <code>#[graphql(default = <expression>)]</code> argument.</p>
<p><strong>TIP</strong>: See more available features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLInputObject.html"><code>#[derive(GraphQLInputObject)]</code></a> attribute.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Scalars">GraphQL scalars</a> represent primitive leaf values in a GraphQL type system: numbers, strings, and booleans.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> provides support for all the <ahref="https://spec.graphql.org/October2021/#sec-Scalars.Built-in-Scalars">built-in scalars</a>.</p>
<p><strong>NOTE</strong>: <ahref="https://spec.graphql.org/October2021#sec-ID"><code>ID</code></a> scalar is <ahref="https://spec.graphql.org/October2021#sec-ID">defined in the GraphQL spec</a> as a type that is serialized as a string, but can be parsed from both a string and an integer.</p>
</blockquote>
<blockquote>
<p><strong>TIP</strong>: There is no built-in support for <code>i64</code>, <code>u64</code>, or other <ahref="https://www.rust-lang.org">Rust</a> integer types, as the <ahref="https://spec.graphql.org/October2021#sel-FAHXJDCAACKB1qb">GraphQL spec doesn't define any built-in scalars for them</a> by default. Instead, to be supported, they should be defined as <ahref="types/scalars.html#custom">custom scalars</a> in a <ahref="https://graphql.org/learn/schema">GraphQL schema</a>.</p>
<p>We can create <ahref="https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars">custom scalars</a> for other primitive values, but they are still <ahref="https://spec.graphql.org/October2021#sel-FAHXJDCAACKB1qb">limited in the data types for representation</a>, and only introduce additional semantic meaning. This, also, often requires coordination with the client library, intended to consume the API we're building.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars">Custom scalars</a> can be defined in <ahref="https://docs.rs/juniper">Juniper</a> by using either <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLScalar.html"><code>#[derive(GraphQLScalar)]</code></a> or <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_scalar.html"><code>#[graphql_scalar]</code></a> attributes, which do work pretty much the same way (except, <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLScalar.html"><code>#[derive(GraphQLScalar)]</code></a> cannot be used on <ahref="https://doc.rust-lang.org/reference/items/type-aliases.html">type aliases</a>).</p>
<p>Quite often, we want to create a <ahref="https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars">custom GraphQL scalar</a> type by just wrapping an existing one, inheriting all its behavior. In <ahref="https://www.rust-lang.org">Rust</a>, this is often called as <ahref="https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html">"newtype pattern"</a>. This may be achieved by providing a <code>#[graphql(transparent)]</code> attribute to the definition:</p>
<p>That's it, now the <code>UserId</code> and <code>MessageId</code><ahref="https://spec.graphql.org/October2021#sec-Scalars">scalars</a> can be used in <ahref="https://graphql.org/learn/schema">GraphQL schema</a>.</p>
<p>We may also customize the definition, to provide more information about our <ahref="https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars">custom scalar</a> in <ahref="https://graphql.org/learn/schema">GraphQL schema</a>:</p>
<p>In case we need to customize <ahref="https://spec.graphql.org/October2021#sec-Value-Resolution">resolving</a> of a <ahref="https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars">custom GraphQL scalar</a> value (change the way it gets executed), the <code>#[graphql(to_output_with = <fn path>)]</code> attribute is the way to do so:</p>
<h3id="input-value-parsing"><aclass="header"href="#input-value-parsing">Input value parsing</a></h3>
<p>Customization of a <ahref="https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars">custom GraphQL scalar</a> value parsing is possible via <code>#[graphql(from_input_with = <fn path>)]</code> attribute:</p>
<p>Customization of which tokens a <ahref="https://spec.graphql.org/October2021#sec-Scalars">custom GraphQL scalar</a> type should be parsed from, is possible via <code>#[graphql(parse_token_with = <fn path>)]</code> or <code>#[graphql(parse_token(<types>)]</code> attributes:</p>
<p><strong>NOTE</strong>: Once we provide all 3 custom functions, there is no sense to follow <ahref="https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html">newtype pattern</a> anymore, as nothing left to inherit.</p>
<p>Instead of providing all custom functions separately, it's possible to provide a module holding the appropriate <code>to_output()</code>, <code>from_input()</code> and <code>parse_token()</code> functions via <code>#[graphql(with = <module path>)]</code> attribute:</p>
<p><strong>TIP</strong>: See more available features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/derive.GraphQLScalar.html"><code>#[derive(GraphQLScalar)]</code></a> and <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_scalar.html"><code>#[graphql_scalar]</code></a> attributes.</p>
<p>For implementing <ahref="https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars">custom scalars</a> on foreign types there is <ahref="https://docs.rs/juniper/0.16.0/juniper/attr.graphql_scalar.html"><code>#[graphql_scalar]</code></a> attribute.</p>
<p><strong>NOTE</strong>: To satisfy <ahref="https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules">orphan rules</a>, we should provide a local <ahref="https://docs.rs/juniper/0.16.0/juniper/trait.ScalarValue.html"><code>ScalarValue</code></a> implementation.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> provides out-of-the-box <ahref="https://spec.graphql.org/October2021#sec-Scalars">GraphQL scalar</a> implementations for some very common <ahref="https://www.rust-lang.org">Rust</a> crates. The types from these crates will be usable in your schemas automatically after enabling the correspondent self-titled <ahref="https://doc.rust-lang.org/cargo/reference/features.html">Cargo feature</a>.</p>
<p><strong><ahref="https://docs.rs/juniper">Juniper</a> follows a <ahref="https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#code-only">code-first</a> approach to define a <ahref="https://graphql.org">GraphQL</a> schema.</strong></p>
<blockquote>
<p><strong>TIP</strong>: For a <ahref="https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#schema-first">schema-first</a> approach, consider using a <ahref="https://docs.rs/juniper-from-schema"><code>juniper-from-schema</code></a> crate for generating a <ahref="https://docs.rs/juniper"><code>juniper</code></a>-based code from a <ahref="https://graphql.org/learn/schema">schema</a> file.</p>
</blockquote>
<p><ahref="https://spec.graphql.org/October2021#sec-Schema">GraphQL schema</a> consists of three <ahref="https://spec.graphql.org/October2021#sec-Objects">object types</a>: a <ahref="https://spec.graphql.org/October2021#sel-FAHTRFCAACChCtpG">query root</a>, a <ahref="https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD">mutation root</a>, and a <ahref="https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX">subscription root</a>.</p>
<blockquote>
<p>The <strong>query</strong> root operation type must be provided and must be an <ahref="https://spec.graphql.org/October2021#sec-Objects">Object</a> type.</p>
<p>The <strong>mutation</strong> root operation type is optional; if it is not provided, the service does not support mutations. If it is provided, it must be an <ahref="https://spec.graphql.org/October2021#sec-Objects">Object</a> type.</p>
<p>Similarly, the <strong>subscription</strong> root operation type is also optional; if it is not provided, the service does not support subscriptions. If it is provided, it must be an <ahref="https://spec.graphql.org/October2021#sec-Objects">Object</a> type.</p>
<p>The <strong>query</strong>, <strong>mutation</strong>, and <strong>subscription</strong> root types must all be different types if provided.</p>
<p>In <ahref="https://docs.rs/juniper">Juniper</a>, the <ahref="https://docs.rs/juniper/0.16.0/juniper/struct.RootNode.html"><code>RootNode</code></a> type represents a <ahref="https://spec.graphql.org/October2021#sec-Schema">schema</a>. When the <ahref="https://spec.graphql.org/October2021#sec-Schema">schema</a> is first created, <ahref="https://docs.rs/juniper">Juniper</a> will traverse the entire object graph and register all types it can find. This means that if we <ahref="schema/../types/objects/index.html">define a GraphQL object</a> somewhere but never use or reference it, it won't be exposed in a <ahref="https://spec.graphql.org/October2021#sec-Schema">GraphQL schema</a>.</p>
<p>Both <ahref="https://spec.graphql.org/October2021#sel-FAHTRFCAACChCtpG">query</a> and <ahref="https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD">mutation</a> objects are regular <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL objects</a>, defined like <ahref="schema/../types/objects/index.html">any other object in Juniper</a>. The <ahref="https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD">mutation</a> and <ahref="https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX">subscription</a> objects, however, are optional, since <ahref="https://spec.graphql.org/October2021#sec-Schema">schemas</a> can be read-only and do not require <ahref="https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX">subscriptions</a>.</p>
<p><strong>TIP</strong>: If <ahref="https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD">mutation</a>/<ahref="https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX">subscription</a> functionality is not needed, consider using the predefined <ahref="https://docs.rs/juniper/0.16.0/juniper/struct.EmptyMutation.html"><code>EmptyMutation</code></a>/<ahref="https://docs.rs/juniper/0.16.0/juniper/struct.EmptySubscription.html"><code>EmptySubscription</code></a> types for stubbing them in a <ahref="https://docs.rs/juniper/0.16.0/juniper/struct.RootNode.html"><code>RootNode</code></a>.</p>
<p><strong>NOTE</strong>: It's considered a <ahref="https://spec.graphql.org/October2021#sec-Root-Operation-Types.Default-Root-Operation-Type-Names">good practice</a> to name <ahref="https://spec.graphql.org/October2021#sel-FAHTRFCAACChCtpG">query</a>, <ahref="https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD">mutation</a>, and <ahref="https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX">subscription</a> root types as <code>Query</code>, <code>Mutation</code>, and <code>Subscription</code> respectively.</p>
</blockquote>
<p>The usage of <ahref="https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX">subscriptions</a> is a little different from the <ahref="https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD">mutation</a> and <ahref="https://spec.graphql.org/October2021#sel-FAHTRFCAACChCtpG">query</a><ahref="https://spec.graphql.org/October2021#sec-Objects">objects</a>, so they are discussed in the <ahref="schema/subscriptions.html">separate chapter</a>.</p>
<p>Many tools in <ahref="https://graphql.org">GraphQL</a> ecosystem require a <ahref="https://graphql.org/learn/schema">schema</a> definition to operate on. With <ahref="https://docs.rs/juniper">Juniper</a> we can export our <ahref="https://spec.graphql.org/October2021#sec-Schema">GraphQL schema</a> defined in <ahref="https://www.rust-lang.org">Rust</a> code either represented in the <ahref="https://graphql.org/learn/schema#type-language">GraphQL schema language</a> or in <ahref="https://www.json.org">JSON</a>.</p>
<p>To generate an <ahref="https://graphql.org/learn/schema#type-language">SDL (schema definition language)</a> representation of a <ahref="https://spec.graphql.org/October2021#sec-Schema">GraphQL schema</a> defined in <ahref="https://www.rust-lang.org">Rust</a> code, the <ahref="https://docs.rs/juniper/0.16.0/juniper/struct.RootNode.html#method.as_sdl"><code>as_sdl()</code> method</a> should be used for the direct extraction (requires enabling the <code>schema-language</code><ahref="https://docs.rs/juniper">Juniper</a> feature):</p>
<p>To export a <ahref="https://spec.graphql.org/October2021#sec-Schema">GraphQL schema</a> defined in <ahref="https://www.rust-lang.org">Rust</a> code as <ahref="https://www.json.org">JSON</a> (often referred to as <code>schema.json</code>), the specially crafted <ahref="https://docs.rs/crate/juniper/latest/source/src/introspection/query.graphql">introspection query</a> should be issued. <ahref="https://docs.rs/juniper">Juniper</a> provides a <ahref="https://docs.rs/juniper/0.16.0/juniper/fn.introspect.html">convenience <code>introspect()</code> function</a> to <ahref="schema/introspection.html">introspect</a> the entire <ahref="https://spec.graphql.org/October2021#sec-Schema">schema</a>, which result can be serialized into <ahref="https://www.json.org">JSON</a>:</p>
let json_result = serde_json::to_string_pretty(&res);
assert!(json_result.is_ok());
}</code></pre></pre>
<blockquote>
<p><strong>TIP</strong>: We still can convert the generated <ahref="https://www.json.org">JSON</a> into a <ahref="https://graphql.org/learn/schema#type-language">GraphQL schema language</a> representation by using tools like <ahref="https://npmjs.com/package/graphql-json-to-sdl"><code>graphql-json-to-sdl</code> command line utility</a>.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Subscription">GraphQL subscriptions</a> are a way to push data from a server to clients requesting real-time messages from a server. <ahref="https://spec.graphql.org/October2021#sec-Subscription">Subscriptions</a> are similar to <ahref="https://spec.graphql.org/October2021#sec-Query">queries</a> in that they specify a set of fields to be delivered to a client, but instead of immediately returning a single answer a result is sent every time a particular event happens on a server.</p>
<p>In order to execute <ahref="https://spec.graphql.org/October2021#sec-Subscription">subscriptions</a> in <ahref="https://docs.rs/juniper">Juniper</a>, we need a coordinator (spawning long-lived connections) and a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a> with <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> resolving into a <ahref="https://docs.rs/futures/latest/futures/stream/trait.Stream.html"><code>Stream</code></a> of elements which will then be returned to a client. The <ahref="https://docs.rs/juniper_subscriptions"><code>juniper_subscriptions</code> crate</a> provides a default implementation of these abstractions.</p>
<p>The <ahref="https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX">subscription root</a> is just a <ahref="https://spec.graphql.org/October2021#sec-Objects">GraphQL object</a>, similar to the <ahref="https://spec.graphql.org/October2021#sel-FAHTRFCAACChCtpG">query root</a> and <ahref="https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD">mutations root</a> that we define for operations in our <ahref="https://spec.graphql.org/October2021#sec-Schema">GraphQL schema</a>. For <ahref="https://spec.graphql.org/October2021#sec-Subscription">subscriptions</a> all fields should be <code>async</code> and return a <ahref="https://docs.rs/futures/latest/futures/stream/trait.Stream.html"><code>Stream</code></a> of some <ahref="https://spec.graphql.org/October2021#sec-Types">GraphQL type</a> values, rather than direct values.</p>
<p><ahref="https://spec.graphql.org/October2021#sec-Subscription">GraphQL subscriptions</a> require a bit more resources than regular <ahref="https://spec.graphql.org/October2021#sec-Query">queries</a> and provide a great vector for <ahref="https://en.wikipedia.org/wiki/Denial-of-service_attack">DoS attacks</a>. This can can bring down a server easily if not handled correctly. The <ahref="https://docs.rs/juniper/0.16.0/juniper/trait.SubscriptionCoordinator.html"><code>SubscriptionCoordinator</code> trait</a> provides coordination logic to enable functionality like <ahref="https://en.wikipedia.org/wiki/Denial-of-service_attack">DoS attacks</a> mitigation and resource limits.</p>
<p>The <ahref="https://docs.rs/juniper/0.16.0/juniper/trait.SubscriptionCoordinator.html"><code>SubscriptionCoordinator</code></a> contains the <ahref="https://spec.graphql.org/October2021#sec-Schema">schema</a> and can keep track of opened connections, handle <ahref="https://spec.graphql.org/October2021#sec-Subscription">subscription</a> start and end, and maintain a global ID for each <ahref="https://spec.graphql.org/October2021#sec-Subscription">subscription</a>. Each time a connection is established, the <ahref="https://docs.rs/juniper/0.16.0/juniper/trait.SubscriptionCoordinator.html"><code>SubscriptionCoordinator</code></a> spawns a [32], which handles a single connection, providing resolver logic for a client stream as well as reconnection and shutdown logic.</p>
<p>While we can implement <ahref="https://docs.rs/juniper/0.16.0/juniper/trait.SubscriptionCoordinator.html"><code>SubscriptionCoordinator</code></a> ourselves, <ahref="https://docs.rs/juniper">Juniper</a> contains a simple and generic implementation called <ahref="https://docs.rs/juniper_subscriptions/latest/juniper_subscriptions/struct.Coordinator.html"><code>Coordinator</code></a>. The <code>subscribe</code> method returns a <ahref="https://doc.rust-lang.org/stable/std/future/trait.Future.html"><code>Future</code></a> resolving into a <code>Result<Connection, GraphQLError></code>, where <ahref="https://docs.rs/juniper_subscriptions/latest/juniper_subscriptions/struct.Connection.html"><code>Connection</code></a> is a <ahref="https://docs.rs/futures/latest/futures/stream/trait.Stream.html"><code>Stream</code></a> of <ahref="https://spec.graphql.org/October2021#sec-Values">values</a> returned by the operation, and a <ahref="https://docs.rs/juniper/0.16.0/juniper/enum.GraphQLError.html"><code>GraphQLError</code></a> is the error when the <ahref="https://spec.graphql.org/October2021#sec-Subscription">subscription operation</a> fails.</p>
<p>For information about serving <ahref="https://spec.graphql.org/October2021#sec-Subscription">GraphQL subscriptions</a> over <ahref="https://en.wikipedia.org/wiki/WebSocket">WebSocket</a>, see the <ahref="schema/../serve/index.html#websocket">"Serving" chapter</a>.</p>
<p>The <ahref="https://spec.graphql.org/October2021#sec-Schema-Introspection">schema introspection</a> system is accessible from the meta-fields <code>__schema</code> and <code>__type</code> which are accessible from the type of the root of a query operation.</p>
<p>Like all meta-fields, these are implicit and do not appear in the fields list in the root type of the query operation.</p>
</blockquote>
<p><ahref="https://graphql.org">GraphQL</a> provides <ahref="https://spec.graphql.org/October2021#sec-Introspection">introspection</a>, allowing to see what <ahref="https://spec.graphql.org/October2021#sel-GAFRJBABABF_jB">queries</a>, <ahref="https://spec.graphql.org/October2021#sel-GAFRJDABABI5C">mutations</a> and <ahref="https://spec.graphql.org/October2021#sel-GAFRJFABABMvpN">subscriptions</a> a <ahref="https://graphql.org">GraphQL</a> server supports at runtime.</p>
<p>Because <ahref="https://spec.graphql.org/October2021#sec-Introspection">introspection</a> queries are just regular <ahref="https://spec.graphql.org/October2021#sel-GAFRJBABABF_jB">GraphQL queries</a>, <ahref="https://docs.rs/juniper">Juniper</a> supports them natively. For example, to get all the names of the types supported, we could <ahref="https://spec.graphql.org/October2021#sec-Execution">execute</a> the following <ahref="https://spec.graphql.org/October2021#sel-GAFRJBABABF_jB">query</a> against <ahref="https://docs.rs/juniper">Juniper</a>:</p>
<p>Disabling introspection in production is a widely debated topic, but we believe it’s one of the first things you can do to harden your GraphQL API in production.</p>
<p><ahref="https://www.apollographql.com/blog/why-you-should-disable-graphql-introspection-in-production">Some security requirements and considerations</a> may mandate to disable <ahref="https://spec.graphql.org/October2021#sec-Schema-Introspection">GraphQL schema introspection</a> in production environments. In <ahref="https://docs.rs/juniper">Juniper</a> this can be achieved by using the <ahref="https://docs.rs/juniper/0.16.0/juniper/struct.RootNode.html#method.disable_introspection"><code>RootNode::disable_introspection()</code></a> method:</p>
type Schema = RootNode<'static, Query, EmptyMutation, EmptySubscription>;
fn main() {
let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new())
.disable_introspection();
let query = "query { __schema { queryType { name } } }";
match juniper::execute_sync(query, None, &schema, &graphql_vars! {}, &()) {
Err(GraphQLError::ValidationError(errs)) => {
assert_eq!(
errs.first().unwrap().message(),
"GraphQL introspection is not allowed, but the operation contained `__schema`",
);
}
res => panic!("expected `ValidationError`, returned: {res:#?}"),
}
}</code></pre></pre>
<blockquote>
<p><strong>NOTE</strong>: Attempt to execute an <ahref="https://spec.graphql.org/October2021#sec-Schema-Introspection">introspection query</a> results in <ahref="https://spec.graphql.org/October2021#sec-Validation">validation</a> error, rather than <ahref="https://spec.graphql.org/October2021#sec-Execution">execution</a> error.</p>
<p>Once we have built a <ahref="serve/../schema/index.html">GraphQL schema</a>, the next obvious step would be to serve it, so clients can interact with our <ahref="https://graphql.org">GraphQL</a> API. Usually, <ahref="https://graphql.org">GraphQL</a> APIs are served via <ahref="https://en.wikipedia.org/wiki/HTTP">HTTP</a>.</p>
<h2id="web-server-frameworks-1"><aclass="header"href="#web-server-frameworks-1">Web server frameworks</a></h2>
<p>Though the <ahref="https://docs.rs/juniper"><code>juniper</code></a> crate doesn't provide a built-in <ahref="https://en.wikipedia.org/wiki/HTTP">HTTP</a> server, the surrounding ecosystem does.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a> officially supports the following widely used and adopted web server frameworks in <ahref="https://www.rust-lang.org">Rust</a> ecosystem:</p>
<p>See their API docs and usage examples (accessible from API docs) for further details of how they should be used.</p>
<blockquote>
<p><strong>NOTE</strong>: All the officially supported web server framework integrations provide a simple and convenient way for exposing <ahref="https://github.com/graphql/graphiql">GraphiQL</a> and/or <ahref="https://github.com/prisma/graphql-playground">GraphQL Playground</a> with the <ahref="serve/../schema/index.html">GraphQL schema</a> along. These powerful tools ease the development process by enabling you to explore and send client requests to the <ahref="https://graphql.org">GraphQL</a> API under development.</p>
<p><strong>NOTE</strong>: <ahref="https://en.wikipedia.org/wiki/WebSocket">WebSocket</a> is a crucial part for serving <ahref="serve/../schema/subscriptions.html">GraphQL subscriptions</a> over <ahref="https://en.wikipedia.org/wiki/HTTP">HTTP</a>.</p>
</blockquote>
<p>There are two widely adopted protocols for serving <ahref="https://graphql.org">GraphQL</a> over <ahref="https://en.wikipedia.org/wiki/WebSocket">WebSocket</a>:</p>
<ol>
<li><ahref="https://github.com/apollographql/subscriptions-transport-ws/blob/v0.11.0/PROTOCOL.md">Legacy <code>graphql-ws</code> GraphQL over WebSocket Protocol</a>, formerly used by <ahref="https://www.apollographql.com">Apollo</a> and the <ahref="https://npmjs.com/package/subscriptions-transport-ws"><code>subscriptions-transport-ws</code> npm package</a>, and now being deprecated.</li>
<li><ahref="https://github.com/enisdenjo/graphql-ws/blob/v5.14.0/PROTOCOL.md">New <code>graphql-transport-ws</code> GraphQL over WebSocket Protocol</a>, provided by the <ahref="https://npmjs.com/package/graphql-ws"><code>graphql-ws</code> npm package</a> and being used by <ahref="https://www.apollographql.com">Apollo</a> as for now.</li>
</ol>
<p>In the <ahref="https://docs.rs/juniper">Juniper</a> ecosystem, both implementations are provided by the <ahref="https://docs.rs/juniper_graphql_ws"><code>juniper_graphql_ws</code></a> crate. Most of the <ahref="serve/index.html#officially-supported">officially supported web server framework integrations</a> are able to serve a <ahref="serve/../schema/index.html">GraphQL schema</a> over <ahref="https://en.wikipedia.org/wiki/WebSocket">WebSocket</a> (including <ahref="serve/../schema/subscriptions.html">subscriptions</a>) and even support <ahref="https://developer.mozilla.org/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#subprotocols">auto-negotiation of the correct protocol based on the <code>Sec-Websocket-Protocol</code> HTTP header value</a>. See their API docs and usage examples (accessible from API docs) for further details of how to do so.</p>
<p>The <ahref="https://graphql.org">GraphQL</a> standard generally assumes that there will be one server request per each client operation to perform (such as a query or mutation). This is conceptually simple but potentially inefficient.</p>
<p>Some client libraries (such as <ahref="https://www.apollographql.com/docs/link/links/batch-http.html"><code>apollo-link-batch-http</code></a>) have the ability to batch operations in a single <ahref="https://en.wikipedia.org/wiki/HTTP">HTTP</a> request to save network round-trips and potentially increase performance. There are <ahref="https://www.apollographql.com/blog/batching-client-graphql-queries#what-are-the-tradeoffs-with-batching">some tradeoffs</a>, though, that should be considered before <ahref="https://www.apollographql.com/blog/batching-client-graphql-queries">batching operations</a>.</p>
<p><ahref="https://docs.rs/juniper">Juniper</a>'s <ahref="serve/index.html#officially-supported">server integration crates</a> support <ahref="https://www.apollographql.com/blog/batching-client-graphql-queries">batching multiple operations</a> in a single <ahref="https://en.wikipedia.org/wiki/HTTP">HTTP</a> request out-of-the-box via <ahref="https://www.json.org">JSON</a> arrays. This makes them compatible with client libraries that support <ahref="https://www.apollographql.com/blog/batching-client-graphql-queries">batch operations</a> without any special configuration.</p>
<blockquote>
<p><strong>NOTE</strong>: If you use a custom server integration, it's <strong>not a hard requirement</strong> to support <ahref="https://www.apollographql.com/blog/batching-client-graphql-queries">batching</a>, as it's not a part of the <ahref="https://spec.graphql.org/October2021">official GraphQL specification</a>.</p>
</blockquote>
<p>Assuming an integration supports <ahref="https://www.apollographql.com/blog/batching-client-graphql-queries">operations batching</a>, for the following GraphQL query:</p>
<pre><codeclass="language-graphql">{
hero {
name
}
}
</code></pre>
<p>The <ahref="https://www.json.org">JSON</a><code>data</code> to <ahref="https://en.wikipedia.org/wiki/POST_(HTTP)">POST</a> for an individual request would be:</p>
<pre><codeclass="language-json">{
"query": "{hero{name}}"
}
</code></pre>
<p>And the response would be in the form:</p>
<pre><codeclass="language-json">{
"data": {
"hero": {
"name": "R2-D2"
}
}
}
</code></pre>
<p>However, if we want to run the same query twice in a single <ahref="https://en.wikipedia.org/wiki/HTTP">HTTP</a> request, the batched <ahref="https://www.json.org">JSON</a><code>data</code> to <ahref="https://en.wikipedia.org/wiki/POST_(HTTP)">POST</a> would be:</p>
<pre><codeclass="language-json">[
{
"query": "{hero{name}}"
},
{
"query": "{hero{name}}"
}
]
</code></pre>
<p>And then, the response would be in the following array form:</p>
<divstyle="break-before: page; page-break-before: always;"></div><h1id="implicit-and-explicit-null"><aclass="header"href="#implicit-and-explicit-null">Implicit and explicit <code>null</code></a></h1>
<blockquote>
<p><ahref="https://graphql.org">GraphQL</a> has two semantically different ways to represent the lack of a value:</p>
<ul>
<li>Explicitly providing the literal value: <strong>null</strong>.</li>
<li>Implicitly not providing a value at all.</li>
</ul>
</blockquote>
<p>There are two ways that a client can submit a <ahref="https://spec.graphql.org/October2021#sec-Null-Value"><code>null</code> value</a> as an <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">argument</a> or a <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a> in a <ahref="https://graphql.org">GraphQL</a> query:</p>
<ol>
<li>Either use an explicit <code>null</code> literal:
<pre><codeclass="language-graphql">{
field(arg: null)
}
</code></pre>
</li>
<li>Or simply omit the <ahref="https://spec.graphql.org/October2021#sec-Language.Arguments">argument</a>, so the implicit default <code>null</code> value kicks in:
<pre><codeclass="language-graphql">{
field
}
</code></pre>
</li>
</ol>
<p>There are some situations where it's useful to know which one exactly has been provided.</p>
<p>For example, let's say we have a function that allows users to perform a "patch" operation on themselves. Let's say our users can optionally have favorite and least favorite numbers, and the input for that might look like this:</p>
<pre><preclass="playground"><codeclass="language-rust edition2021">/// Updates user attributes. Fields that are [`None`] are left as-is.
struct UserPatch {
/// If [`Some`], updates the user's favorite number.
favorite_number: Option<Option<i32>>,
/// If [`Some`], updates the user's least favorite number.
<p>To set a user's favorite number to 7, we would set <code>favorite_number</code> to <code>Some(Some(7))</code>. In <ahref="https://graphql.org">GraphQL</a>, that might look like this:</p>
<p>To unset the user's favorite number, we would set <code>favorite_number</code> to <code>Some(None)</code>. In <ahref="https://graphql.org">GraphQL</a>, that might look like this:</p>
<p>And if we want to leave the user's favorite number alone, just set it to <code>None</code>. In <ahref="https://graphql.org">GraphQL</a>, that might look like this:</p>
<p>The last two cases rely on being able to distinguish between <ahref="https://spec.graphql.org/October2021#sel-EAFdRDHAAEJDAoBxzT">explicit and implicit <code>null</code></a>.</p>
<p>Unfortunately, plain <code>Option</code> is not capable to distinguish them. That's why in <ahref="https://docs.rs/juniper">Juniper</a>, this can be done using the <ahref="https://docs.rs/juniper/0.16.0/juniper/enum.Nullable.html"><code>Nullable</code></a> type:</p>
<p>A common issue with <ahref="https://graphql.org">GraphQL</a> server implementations is how the <ahref="https://spec.graphql.org/October2021#sec-Executing-Fields">resolvers</a> query their datasource. With a naive and straightforward approach we quickly run into the N+1 problem, resulting in a large number of unnecessary database queries or <ahref="https://en.wikipedia.org/wiki/HTTP">HTTP</a> requests.</p>
<p>Let's say we want to list a bunch of <code>cult</code>s <code>persons</code> were in:</p>
<pre><codeclass="language-graphql">query {
persons {
id
name
cult {
id
name
}
}
}
</code></pre>
<p>Once the <code>persons</code><ahref="https://spec.graphql.org/October2021#sec-List">list</a> has been <ahref="https://spec.graphql.org/October2021#sec-Executing-Fields">resolved</a>, a separate <ahref="https://en.wikipedia.org/wiki/SQL">SQL</a> query is run to find the <code>cult</code> of each <code>Person</code>. We can see how this could quickly become a problem.</p>
<pre><codeclass="language-sql">SELECT id, name, cult_id FROM persons;
SELECT id, name FROM cults WHERE id = 1;
SELECT id, name FROM cults WHERE id = 2;
SELECT id, name FROM cults WHERE id = 1;
SELECT id, name FROM cults WHERE id = 3;
SELECT id, name FROM cults WHERE id = 4;
SELECT id, name FROM cults WHERE id = 1;
SELECT id, name FROM cults WHERE id = 2;
-- and so on...
</code></pre>
<p>There are several ways how this problem may be resolved in <ahref="https://docs.rs/juniper">Juniper</a>. The most common ones are:</p>
<p>DataLoader pattern, named after the correspondent <ahref="https://github.com/graphql/dataloader"><code>dataloader</code> NPM package</a>, represents a mechanism of batching and caching data requests in a delayed manner for solving the <ahref="advanced/n_plus_1.html">N+1 problem</a>.</p>
<blockquote>
<p>A port of the "Loader" API originally developed by <ahref="https://github.com/schrockn">@schrockn</a> at Facebook in 2010 as a simplifying force to coalesce the sundry key-value store back-end APIs which existed at the time. At Facebook, "Loader" became one of the implementation details of the "Ent" framework, a privacy-aware data entity loading and caching layer within web server product code. This ultimately became the underpinning for Facebook's GraphQL server implementation and type definitions.</p>
</blockquote>
<p>In <ahref="https://www.rust-lang.org">Rust</a> ecosystem, DataLoader pattern is introduced with the <ahref="https://docs.rs/crate/dataloader"><code>dataloader</code> crate</a>, naturally usable with <ahref="https://docs.rs/juniper">Juniper</a>.</p>
<p>Let's remake our <ahref="advanced/n_plus_1.html">example of N+1 problem</a>, so it's solved by applying the DataLoader pattern:</p>
<p><ahref="https://docs.rs/dataloader/latest/dataloader/cached/index.html"><code>dataloader::cached</code></a> provides a <ahref="https://en.wikipedia.org/wiki/Memoization">memoization</a> cache: after <code>BatchFn::load()</code> is called once with given keys, the resulting values are cached to eliminate redundant loads.</p>
<p>DataLoader caching does not replace <ahref="https://redis.io">Redis</a>, <ahref="https://memcached.org">Memcached</a>, or any other shared application-level cache. DataLoader is first and foremost a data loading mechanism, and its cache only serves the purpose of not repeatedly loading the same data <ahref="https://github.com/graphql/dataloader#caching">in the context of a single request</a>.</p>
<blockquote>
<p><strong>WARNING</strong>: A DataLoader should be created per-request to avoid risk of bugs where one client is able to load cached/batched data from another client outside its authenticated scope. Creating a DataLoader within an individual resolver will prevent batching from occurring and will nullify any benefits of it.</p>
<p>For a full example using DataLoaders in <ahref="https://docs.rs/juniper">Juniper</a> check out the <ahref="https://github.com/jayy-lmao/rust-graphql-docker"><code>jayy-lmao/rust-graphql-docker</code> repository</a>.</p>
<p>In backtracking algorithms, <strong>look ahead</strong> is the generic term for a subprocedure that attempts to foresee the effects of choosing a branching variable to evaluate one of its values. The two main aims of look-ahead are to choose a variable to evaluate next and to choose the order of values to assign to it.</p>
</blockquote>
<p>In <ahref="https://graphql.org">GraphQL</a>, look-ahead machinery allows us to introspect the currently <ahref="https://spec.graphql.org/October2021#sec-Execution">executed</a><ahref="https://spec.graphql.org/October2021#sec-Language.Operations%5C">GraphQL operation</a> to see which <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> has been actually selected by it.</p>
<p>In <ahref="https://docs.rs/juniper">Juniper</a>, it's represented by the <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.Executor.html#method.look_ahead"><code>Executor::look_ahead()</code></a> method.</p>
<p><strong>TIP</strong>: <code>S: ScalarValue</code> type parameter on the method is required here to keep the <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.Executor.html"><code>Executor</code></a> being generic over <ahref="https://docs.rs/juniper/0.16.0/juniper/trait.ScalarValue.html"><code>ScalarValue</code></a> types. We, instead, could have used the <ahref="https://docs.rs/juniper/0.16.0/juniper/enum.DefaultScalarValue.html"><code>DefaultScalarValue</code></a>, which is the default <ahref="https://docs.rs/juniper/0.16.0/juniper/trait.ScalarValue.html"><code>ScalarValue</code></a> type for the <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.Executor.html"><code>Executor</code></a>, and make our code more ergonomic, but less flexible and generic.</p>
<p>Naturally, look-ahead machinery allows us to solve <ahref="advanced/n_plus_1.html">the N+1 problem</a> by introspecting the requested fields and performing loading in batches eagerly, before actual resolving of those fields:</p>
<p>See more available look-ahead features in the API docs of the <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.LookAheadSelection.html"><code>LookAheadSelection</code></a> and the <ahref="https://docs.rs/juniper/0.16.0/juniper/executor/struct.LookAheadChildren.html"><code>LookAheadChildren</code></a>.</p>
<p>As a further evolution of the <ahref="advanced/lookahead.html#n1-problem">dealing with the N+1 problem via look-ahead</a>, we may systematically remodel <ahref="https://www.rust-lang.org">Rust</a> types mapping to <ahref="https://graphql.org">GraphQL</a> ones in the way to encourage doing eager preloading of data for its <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">fields</a> and using the already preloaded data when resolving a particular <ahref="https://spec.graphql.org/October2021#sec-Language.Fields">field</a>.</p>
<p>At the moment, this approach is represented with the <ahref="https://docs.rs/juniper-eager-loading"><code>juniper-eager-loading</code></a> crate for <ahref="https://docs.rs/juniper">Juniper</a>.</p>
<blockquote>
<p><strong>NOTE</strong>: Since this library requires <ahref="https://docs.rs/juniper-from-schema"><code>juniper-from-schema</code></a>, it's best first to become familiar with it.</p>
</blockquote>
<!-- TODO: Provide example of solving the problem from "N+1 chapter" once `juniper-eager-loading` support the latest `juniper`. -->
<p>From <ahref="https://docs.rs/juniper-eager-loading/latest/juniper_eager_loading#how-this-library-works-at-a-high-level">"How this library works at a high level"</a> and <ahref="https://docs.rs/juniper-eager-loading/latest/juniper_eager_loading#a-real-example">"A real example"</a> sections of <ahref="https://docs.rs/juniper-eager-loading"><code>juniper-eager-loading</code></a> documentation:</p>
<blockquote>
<h3id="how-this-library-works-at-a-high-level"><aclass="header"href="#how-this-library-works-at-a-high-level">How this library works at a high level</a></h3>
<p>If you have a GraphQL type like this</p>
<pre><codeclass="language-graphql">type User {
id: Int!
country: Country!
}
</code></pre>
<p>You might create the corresponding Rust model type like this:</p>
<p>For a full example using eager loading in <ahref="https://docs.rs/juniper">Juniper</a> check out the <ahref="https://github.com/davidpdrsn/graphql-app-example"><code>davidpdrsn/graphql-app-example</code> repository</a>.</p>