GraphQL with async-graphql

Learn what GraphQL is, how to define a schema with async-graphql, serve it from Axum, query and mutate it, and explore it with GraphiQL

GraphQL is a way to ask a server for exactly the data you want, in one request, using a query the client writes. Instead of a fixed set of routes that each return a fixed shape, the server exposes one endpoint and a schema that describes the types and the fields available. The client writes a query naming the fields it wants, and the server answers with a JSON object shaped like the query. The async-graphql crate builds such a server in Rust, and the async-graphql-axum crate connects it to an Axum router. This page builds one, queries it, mutates it, and explores it in the browser.

Where This Fits

A REST API answers a fixed shape per route. A client that needs a book's title and its author's name makes one call, or two calls to two routes, and gets everything those routes return, wanted or not. A client that needs three related things makes three calls. GraphQL changes the bargain: the client describes the shape it wants, and the server fills it in, in one round trip. The cost is a schema to define, a query language to learn, and a server that must resolve each field the client asks for. The benefit is that the client stops over-fetching and stops chaining calls.

Think of a buffet against a set menu. The set menu gives everyone the same courses, whether they want them or not. The buffet lets each person take what they want and leave the rest. REST is the set menu. GraphQL is the buffet, and the schema is the list of dishes on offer.

The Smallest Working Version

One query root, two fields, one endpoint, and the GraphiQL explorer page. The query root is a struct with methods, and each method becomes a field in the schema.

Cargo.toml
[package]
name = "books-graphql"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
async-graphql = "7"
async-graphql-axum = "7"
src/lib.rs
use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use async_graphql::http::GraphiQLSource;
use axum::{Extension, Router, response::Html, routing::{get, post}};

struct Query;

#[Object]
impl Query {
    async fn greeting(&self, name: String) -> String {
        format!("Hello, {name}!")
    }

    async fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}

type ApiSchema = Schema<Query, EmptyMutation, EmptySubscription>;

async fn graphql_handler(schema: Extension<ApiSchema>, req: GraphQLRequest) -> GraphQLResponse {
    schema.execute(req.into_inner()).await.into()
}

async fn graphiql() -> Html<String> {
    Html(GraphiQLSource::build().endpoint("/graphql").finish())
}

pub fn app() -> Router {
    let schema = Schema::build(Query, EmptyMutation, EmptySubscription).finish();
    Router::new()
        .route("/graphql", post(graphql_handler))
        .route("/graphiql", get(graphiql))
        .layer(Extension(schema))
}
src/main.rs
use books_graphql::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}

Run it with cargo run and send a query with curl. A GraphQL query is a POST to /graphql with a JSON body holding the query string:

curl -s -X POST http://127.0.0.1:3000/graphql -H "Content-Type: application/json" -d '{"query": "{ greeting(name: \"Ada\") add(a: 2, b: 3) }"}'

On the machine used to check this page, the answer was:

{"data":{"greeting":"Hello, Ada!","add":5}}

One request asked for two fields, and the answer holds both, shaped exactly like the query. Ask for only one field, and the answer holds only that one:

curl -s -X POST http://127.0.0.1:3000/graphql -H "Content-Type: application/json" -d '{"query": "{ add(a: 10, b: 32) }"}'
{"data":{"add":42}}

Open http://127.0.0.1:3000/graphiql in a browser for the GraphiQL explorer, a page where queries can be written, run, and autocompleted against the live schema. It is the GraphQL equivalent of the Swagger UI page: the schema rendered as a tool, with a way to try it.

Working Setup:

If the curl query returns {"data":{"greeting":"Hello, Ada!","add":5}} and the GraphiQL page loads in the browser, the schema is built, the endpoint is wired, and the explorer can see it. If the query returns an errors array instead of data, the query text is the place to look, and the error message names the problem field.

The Pieces, One at a Time

1. The query root is a struct with methods

struct Query;

#[Object]
impl Query {
    async fn greeting(&self, name: String) -> String {
        format!("Hello, {name}!")
    }

    async fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}

Query is an empty struct. The #[Object] attribute on its implementation block turns each method into a field of the GraphQL query type. The method name becomes the field name. The arguments become the field's arguments, and the return type becomes the field's type. A String argument becomes a GraphQL String! argument, because it is required. An i32 becomes an Int. The method can be async, and it usually is, because a field often reads from a database or another service. The struct holds no data itself. It is a namespace for the fields.

2. The schema ties the roots together

type ApiSchema = Schema<Query, EmptyMutation, EmptySubscription>;

let schema = Schema::build(Query, EmptyMutation, EmptySubscription).finish();

A schema has three roots: the query root, the mutation root, and the subscription root. A query reads data. A mutation changes data. A subscription streams data over time. The smallest version has only a query root, so the other two are EmptyMutation and EmptySubscription, placeholders that say there is nothing there. Schema::build takes the three roots and returns a builder, and .finish() produces the schema value. The schema is the object the handler executes queries against, and it is also the object the explorer reads to show the available fields.

3. The handler executes the request

async fn graphql_handler(schema: Extension<ApiSchema>, req: GraphQLRequest) -> GraphQLResponse {
    schema.execute(req.into_inner()).await.into()
}

The handler takes two things: the schema, from an Axum Extension layer, and the request, as a GraphQLRequest extractor from async-graphql-axum. The extractor parses the JSON body into a GraphQL request, rejecting a malformed body before the handler runs. schema.execute(...) runs the query: it parses the query string, checks it against the schema, calls the resolver methods for the fields asked for, and builds the answer. The result converts into a GraphQLResponse, which Axum sends back as JSON. The handler is three lines because the library does the work. The work is in the resolvers.

4. GraphiQL is a page that reads the schema

async fn graphiql() -> Html<String> {
    Html(GraphiQLSource::build().endpoint("/graphql").finish())
}

GraphiQLSource::build() builds the HTML for the explorer page, and .endpoint("/graphql") tells the page where to send the queries it runs. The handler returns that HTML, and the route serves it as a GET. The page fetches the schema from the endpoint when it loads, which is how it offers autocomplete for field names. The page is a development tool, the same way the Swagger UI page is, and the same judgement applies to shipping it in production.

The Schema Is the Contract:

A client can only ask for fields the schema defines. Adding a field to the query root adds it to the schema, and removing a method removes it from the schema, which breaks clients that ask for it. The schema is versioned by its contents, not by a number, so a change to a resolver is a change to the contract, and it deserves the same care as changing a REST route.

The Concept Behind It

The core idea is that the client chooses the shape of the answer. In REST, the server chooses the shape, and the client takes what it is given. In GraphQL, the query is the shape, and the server fills it in. That inversion is the whole difference, and everything else follows from it. The server must be able to resolve any combination of fields the client asks for, which is why resolvers are small functions per field rather than one function per route. The client must be able to write the query, which is why the schema is introspectable: a client can ask the server what fields exist, and tools can offer autocomplete from the answer.

The answer is always JSON, and it always has a data key holding the shaped result. Errors do not change the status code. A query that asks for a field that does not exist returns HTTP 200 with an errors array and a null data, as the example below shows. That surprises people who expect a 400, and it is deliberate: the request reached the server and was processed, and the result of that processing is a GraphQL error, not an HTTP error. Only a request that is not GraphQL at all, such as a malformed JSON body, gets an HTTP error.

A Richer Example with Types, a Mutation, and Shared State

A greeting and an addition show the mechanics. A book catalogue shows the shape of a real API: a list of objects, a query that returns them, and a mutation that adds one, all sharing one in-memory store.

src/lib.rs
use async_graphql::{Context, EmptySubscription, InputObject, Object, Schema, SimpleObject};
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use async_graphql::http::GraphiQLSource;
use axum::{Extension, Router, response::Html, routing::{get, post}};
use std::sync::{Arc, RwLock};

#[derive(SimpleObject, Clone)]
struct Book {
    id: i32,
    title: String,
    author: String,
}

#[derive(InputObject)]
struct NewBook {
    title: String,
    author: String,
}

type Store = Arc<RwLock<Vec<Book>>>;

struct Query;

#[Object]
impl Query {
    async fn greeting(&self, name: String) -> String {
        format!("Hello, {name}!")
    }

    async fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }

    async fn books(&self, ctx: &Context<'_>) -> Vec<Book> {
        ctx.data::<Store>().unwrap().read().unwrap().clone()
    }
}

struct Mutation;

#[Object]
impl Mutation {
    async fn add_book(&self, ctx: &Context<'_>, input: NewBook) -> Book {
        let store = ctx.data::<Store>().unwrap();
        let mut books = store.write().unwrap();
        let book = Book { id: books.len() as i32 + 1, title: input.title, author: input.author };
        books.push(book.clone());
        book
    }
}

type ApiSchema = Schema<Query, Mutation, EmptySubscription>;

async fn graphql_handler(schema: Extension<ApiSchema>, req: GraphQLRequest) -> GraphQLResponse {
    schema.execute(req.into_inner()).await.into()
}

async fn graphiql() -> Html<String> {
    Html(GraphiQLSource::build().endpoint("/graphql").finish())
}

pub fn app() -> Router {
    let store: Store = Arc::new(RwLock::new(vec![Book {
        id: 1,
        title: "The Rust Book".into(),
        author: "The Rust Team".into(),
    }]));
    let schema = Schema::build(Query, Mutation, EmptySubscription)
        .data(store)
        .finish();
    Router::new()
        .route("/graphql", post(graphql_handler))
        .route("/graphiql", get(graphiql))
        .layer(Extension(schema))
}

Five new ideas appear here. SimpleObject derives a GraphQL object type from a struct automatically, generating a getter for each field, so a Book becomes a type with id, title, and author fields and no hand written resolvers. InputObject derives an input type, which is a type the client sends rather than receives, so NewBook has the fields the mutation accepts but no id, because the server assigns the id. Context is the per-request bag of values the resolvers can read, and ctx.data::<Store>() pulls the shared store out of it. The store itself is put into the schema builder with .data(store), which makes it available to every resolver. And Mutation replaces EmptyMutation in the schema type, so the schema now has a mutation root with one field, add_book.

Run it and try the mutation:

curl -s -X POST http://127.0.0.1:3000/graphql -H "Content-Type: application/json" -d '{"query": "mutation { addBook(input: {title: \"Dune\", author: \"Frank Herbert\"}) { id title author } }"}'
{"data":{"addBook":{"id":2,"title":"Dune","author":"Frank Herbert"}}}

The mutation returns the created book, with the fields the query asked for, and nothing else. Ask for the list:

curl -s -X POST http://127.0.0.1:3000/graphql -H "Content-Type: application/json" -d '{"query": "{ books { id title } }"}'
{"data":{"books":[{"id":1,"title":"The Rust Book"},{"id":2,"title":"Dune"}]}}

The query asked for id and title only, and the answer holds only those two fields, even though the Book type also has author. The client chose the shape. Ask for a field that does not exist, and the error is precise:

curl -s -X POST http://127.0.0.1:3000/graphql -H "Content-Type: application/json" -d '{"query": "{ noSuchField }"}'
{"data":null,"errors":[{"message":"Unknown field \"noSuchField\" on type \"Query\".","locations":[{"line":1,"column":3}]}]}

The answer is HTTP 200, the data is null, and the error names the field, the type, and the exact position in the query. That message is the schema enforcing itself, and it is the reason a client can learn the API by trying it.

Mutations Run in Order, Queries May Run in Parallel:

Fields in a single query may be resolved in parallel, because they do not depend on each other. Fields in a mutation run one after another, in the order written, because mutations change things and order matters. A mutation that adds two books runs the first add before the second, and the ids come out in order.

Variables, Fragments, and Aliases

A query written as a string with values baked in is fine for curl. A real client writes the query once and sends different values with it, using variables. The query declares the variables, and the request body carries them separately from the query text.

curl -s -X POST http://127.0.0.1:3000/graphql -H "Content-Type: application/json" -d '{"query": "query Add($a: Int!, $b: Int!) { add(a: $a, b: $b) }", "variables": {"a": 10, "b": 32}}'
{"data":{"add":42}}

The $a: Int! declares a variable of integer type, required, and the variables object supplies the values. The same query can be sent with different variables without rewriting the text, which is how clients cache queries and how the server can tell two requests apart by their variables rather than their text.

Two more query features are worth knowing by name. An alias lets the same field be asked twice with different arguments, as in first: books and second: books, so the answer holds both under different names. A fragment lets a set of fields be written once and reused in several places in the query, which keeps long queries readable. Both are part of the query language, not of the server, and they work with any schema.

Subscriptions, in Brief

The third root, EmptySubscription in these examples, is for data that arrives over time. A subscription is a query that stays open, and the server sends a new answer each time the underlying data changes, over a WebSocket. A chat message feed or a live scoreboard is the classic case. Subscriptions need the WebSocket machinery from async-graphql-axum, and they change the deployment, because a connection that stays open is different from a request that ends. They are named here so the third root is not a mystery, and they are not built here, because they are a topic of their own size.

What the Flow Looks Like

Client POSTs {"query": "{ books { id title } }"} to /graphql
        |
        v
GraphQLRequest extractor parses the JSON body
        |
        v
Schema parses the query string and checks it
        |
        v
Resolver for books runs, reads the store from Context
        |
        v
Each requested field is resolved on the returned books
        |
        v
Answer is shaped like the query and sent as JSON
        |
        v
{"data":{"books":[{"id":1,"title":"The Rust Book"}]}}

The schema is the gatekeeper in the middle. A query that names a field the schema does not have fails there, before any resolver runs, which is why the error message can name the exact position of the mistake.

Testing It

A schema can be tested without a server at all, by executing a query string against it directly. That tests the resolvers and the schema in one move.

tests/app_test.rs
use async_graphql::{EmptyMutation, EmptySubscription, Schema};
use books_graphql::{Query, Mutation};
use serde_json::Value;

#[tokio::test]
async fn add_query_returns_the_sum() {
    let schema = Schema::build(Query, Mutation, EmptySubscription).finish();
    let response = schema.execute("{ add(a: 2, b: 3) }").await;
    assert!(response.errors.is_empty());
    let data = response.data.into_json().unwrap();
    assert_eq!(data["add"], Value::from(5));
}

That test needs the Query and Mutation structs to be public in the library, and the store to be built the same way the application builds it, which is a small restructuring of the lib.rs above. The test executes a query string directly on the schema, checks there are no errors, and checks the data. It does not test the HTTP layer. A second test through the router, sending a POST to /graphql and checking the JSON body, covers the HTTP layer, and the two tests together cover the whole path. The direct test is fast and precise. The router test proves the endpoint is wired.

The test needs no new dev dependencies beyond what the project already has, because async-graphql and serde_json are main dependencies.

A Resolver That Panics Fails the Whole Query:

A resolver that panics, for example by unwrapping a missing value from the context, fails the entire query, not just its own field. The ctx.data::<Store>().unwrap() calls in the examples are safe only because the application always puts the store into the schema. If a second schema is built without it, those unwraps panic. Guard the data access or guarantee the data is always present, and never let a resolver panic on a path a client can reach.

Common Beginner Mistakes

Writing a REST shape inside GraphQL

A schema with one field per REST route, each returning a fixed shape, gains nothing from GraphQL and pays all of its costs. The benefit comes from fields that compose: a book with an author field, an author with a books field, each resolved on demand, so the client walks the graph of types instead of calling routes. If the schema is a list of routes in disguise, the API would have been simpler as REST.

Returning everything and letting the client filter

A resolver that loads a whole table and returns it, trusting the client to pick the fields it wants, does the work for the fields nobody asked for. The schema knows which fields were requested, and a careful resolver reads only those. For a small in-memory store the cost is invisible. For a database it is the difference between one column and a whole row, and the N+1 problem, where one query for a list turns into one query per item for a nested field, lives exactly here. The fix is batching, which is a deeper topic, and the first step is noticing that the resolver is doing work the query did not ask for.

Treating errors as HTTP errors

A GraphQL error arrives with HTTP 200 and a null data. A client that checks only the status code will think the request succeeded and then crash on the missing data. A client must check the errors array in the body. A server that wants an HTTP error for a bad request must return it from a layer before the GraphQL handler runs, because once the handler runs, the errors belong to GraphQL.

Forgetting that the endpoint is one route for everything

Every query and every mutation goes to the same /graphql route. Rate limiting, authentication, and logging apply to that one route, and they cannot distinguish a cheap query from an expensive one by path alone. An expensive query, one that asks for a thousand nested items, costs far more than a cheap one, and the server needs a defence against it, such as a limit on query depth or complexity. That defence is part of operating a GraphQL server, and it is the reason the single endpoint is both the strength and the risk of the design.

Final Complete Example

Here is everything from the page put together: the book types, the query and mutation roots, the shared store, the handler, the explorer page, and the server.

src/lib.rs
use async_graphql::{Context, EmptySubscription, InputObject, Object, Schema, SimpleObject};
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use async_graphql::http::GraphiQLSource;
use axum::{Extension, Router, response::Html, routing::{get, post}};
use std::sync::{Arc, RwLock};

#[derive(SimpleObject, Clone)]
struct Book {
    id: i32,
    title: String,
    author: String,
}

#[derive(InputObject)]
struct NewBook {
    title: String,
    author: String,
}

type Store = Arc<RwLock<Vec<Book>>>;

struct Query;

#[Object]
impl Query {
    async fn greeting(&self, name: String) -> String {
        format!("Hello, {name}!")
    }

    async fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }

    async fn books(&self, ctx: &Context<'_>) -> Vec<Book> {
        ctx.data::<Store>().unwrap().read().unwrap().clone()
    }
}

struct Mutation;

#[Object]
impl Mutation {
    async fn add_book(&self, ctx: &Context<'_>, input: NewBook) -> Book {
        let store = ctx.data::<Store>().unwrap();
        let mut books = store.write().unwrap();
        let book = Book { id: books.len() as i32 + 1, title: input.title, author: input.author };
        books.push(book.clone());
        book
    }
}

type ApiSchema = Schema<Query, Mutation, EmptySubscription>;

async fn graphql_handler(schema: Extension<ApiSchema>, req: GraphQLRequest) -> GraphQLResponse {
    schema.execute(req.into_inner()).await.into()
}

async fn graphiql() -> Html<String> {
    Html(GraphiQLSource::build().endpoint("/graphql").finish())
}

pub fn app() -> Router {
    let store: Store = Arc::new(RwLock::new(vec![Book {
        id: 1,
        title: "The Rust Book".into(),
        author: "The Rust Team".into(),
    }]));
    let schema = Schema::build(Query, Mutation, EmptySubscription)
        .data(store)
        .finish();
    Router::new()
        .route("/graphql", post(graphql_handler))
        .route("/graphiql", get(graphiql))
        .layer(Extension(schema))
}
src/main.rs
use books_graphql::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}
Cargo.toml
[package]
name = "books-graphql"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
async-graphql = "7"
async-graphql-axum = "7"

Run the server with cargo run, send the query for greeting and add, run the mutation to add Dune, and open http://127.0.0.1:3000/graphiql to explore the schema in the browser.

Summary

The single most important insight is that GraphQL moves the choice of shape from the server to the client. The server defines the types and the resolvers. The client writes the query that picks the fields. One endpoint serves every shape, the answer is shaped like the question, and the schema is the contract that makes the whole thing checkable before any resolver runs. That inversion is what makes a client able to ask for exactly what it needs in one round trip, and it is also what makes the server responsible for resolving any combination of fields the client can write.

The decision framework follows from that. Choose GraphQL when clients need different shapes of the same data, when over-fetching costs real bandwidth or real round trips, and when the team can carry a schema and its resolvers as a first class part of the service. Choose REST when the shapes are fixed, the clients are simple, and the cost of a schema outweighs the benefit of flexible queries. And whichever is chosen, remember that the endpoint is one route for everything, so the defences that REST gets for free from its many routes, per-route limits and per-route auth, have to be built deliberately for the single GraphQL endpoint.