GraphQL

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

As FastAPI is based on the ASGI standard, it’s very easy to integrate any GraphQL library also compatible with ASGI.

You can combine normal FastAPI path operations with GraphQL on the same application.

Tip

GraphQL solves some very specific use cases.

It has advantages and disadvantages when compared to common web APIs.

Make sure you evaluate if the benefits for your use case compensate the drawbacks. 🤓

GraphQL Libraries

Here are some of the GraphQL libraries that have ASGI support. You could use them with FastAPI:

GraphQL with Strawberry

If you need or want to work with GraphQL, Strawberry is the recommended library as it has the design closest to FastAPI’s design, it’s all based on type annotations.

Depending on your use case, you might prefer to use a different library, but if you asked me, I would probably suggest you try Strawberry.

Here’s a small preview of how you could integrate Strawberry with FastAPI:

  1. import strawberry
  2. from fastapi import FastAPI
  3. from strawberry.asgi import GraphQL
  4. @strawberry.type
  5. class User:
  6. name: str
  7. age: int
  8. @strawberry.type
  9. class Query:
  10. @strawberry.field
  11. def user(self) -> User:
  12. return User(name="Patrick", age=100)
  13. schema = strawberry.Schema(query=Query)
  14. graphql_app = GraphQL(schema)
  15. app = FastAPI()
  16. app.add_route("/graphql", graphql_app)
  17. app.add_websocket_route("/graphql", graphql_app)

You can learn more about Strawberry in the Strawberry documentation.

And also the docs about Strawberry with FastAPI.

Older GraphQLApp from Starlette

Previous versions of Starlette included a GraphQLApp class to integrate with Graphene.

It was deprecated from Starlette, but if you have code that used it, you can easily migrate to starlette-graphene3, that covers the same use case and has an almost identical interface.

Tip

If you need GraphQL, I still would recommend you check out Strawberry, as it’s based on type annotations instead of custom classes and types.

Learn More

You can learn more about GraphQL in the official GraphQL documentation.

You can also read more about each those libraries described above in their links.