Skip to content

Queries and Mutations

Queries and mutations in GraphQL are the way any consumer will interact with the server serving the GraphQL API.

Exposing them using FastGraphQL is very straightforward as we saw in the example in the previous section.

Let us go a little deeper into how to define them.

Queries and mutation in Python code

FastGraphQL handles queries and mutations as python functions that have type annotations for all its parameters and return type.

Can Query act as a mutation?

"Because there is no restriction on what can be done inside resolvers, technically there’s nothing stopping somebody from making Queries act as mutations, taking inputs and executing state-changing logic.

In practice such queries break the contract with client libraries such as Apollo-Client that do client-side caching and state management, resulting in non-responsive controls or inaccurate information being displayed in the UI as the library displays cached data before redrawing it to display an actual response from the GraphQL."

Quote from Ariadne GraphQL.

Queries

As you have already noticed in the previous chapters, defining queries is as simple as annotating a python function with FastGraphQL.query(). Let's see again the first tutorial example:

main.py
from fastapi import FastAPI
from fastgraphql import FastGraphQL
from fastgraphql.fastapi import make_ariadne_fastapi_router

app = FastAPI()
fast_graphql = FastGraphQL()


@fast_graphql.query()
def hello() -> str:
    return "Hello FastGraphQL!!!"


app.include_router(make_ariadne_fastapi_router(fast_graphql=fast_graphql))

Mutation

Similar to queries, mutations are defined by annotating a method with FastGraphQL.mutation(). Let's see an example:

main.py
from fastapi import FastAPI
from fastgraphql import FastGraphQL
from fastgraphql.fastapi import make_ariadne_fastapi_router

app = FastAPI()
fast_graphql = FastGraphQL()


@fast_graphql.mutation()
def dummy_mutation() -> str:
    ...  # Implement some state-changing logic
    return "Done!"


app.include_router(make_ariadne_fastapi_router(fast_graphql=fast_graphql))