English 中文(简体)
FastAPI - Using GraphQL
  • 时间:2024-12-22

FastAPI - Using GraphQL


Previous Page Next Page  

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 cpent.

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

    Strawberry

    Ariadne

    Tartiflette

    Graphene

FastAPI’s official documentation recommends using Strawberry pbrary 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.


@strawberry.type
class Book:
   title: str
   author: str
   price: int

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


@strawberry.type
class Query:
   @strawberry.field
   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 apppcation 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 Advertisements