FastAPI - Using GraphQL

Facebook developed GraphQL in 2012, a new API standard with the intention of optimizing RESTful API Calls. GraphQL is the data query and manipulation language for the API. GraphQL is more flexible, efficient, and accurate as compared to REST. A GraphQL server provides only a single endpoint and responds with the precise data required by the client.

As GraphQL is compatible with ASGI, it can be easily integrated with a FastAPI application. There are many Python libraries for GraphQL. Some of them are listed below −

  • Strawberry

  • Ariadne

  • Tartiflette

  • Graphene

FastAPI’s official documentation recommends using Strawberry library as its design is also based on type annotations (as in the case of FastAPI itself).

In order to integrate GraphQL with a FastAPI app, first decorate a Python class as Strawberry type.

class Book:
   title: str
   author: str
   price: int

Next, declare a Query class containing a function that returns a Book object.

class Query:
   def book(self) -> Book:
   return Book(title="Computer Fundamentals", author="Sinha", price=300)

Use this Query class as the parameter to obtain Strawberry.Schema object

schema = strawberry.Schema(query=Query)

Then declare the objects of both GraphQL class and FastAPI application class.

graphql_app = GraphQL(schema)
app = FastAPI()

Finally, add routes to the FastAPI object and run the server.

app.add_route("/book", graphql_app)
app.add_websocket_route("/book", graphql_app)

Visit http://localhost:8000/book in the browser. An in-browser GraphQL IDE opens up.

FastAPI Using GraphQL

Below the commented section, enter the following query using the Explorer bar of the Graphiql IDE. Run the query to display the result in the output pane.

FastAPI Using GraphQL