FastAPI - 使用GraphQL



Facebook於2012年開發了GraphQL,這是一種新的API標準,旨在最佳化RESTful API呼叫。GraphQL是API的資料查詢和操作語言。與REST相比,GraphQL更靈活、更高效、更準確。GraphQL伺服器只提供單個端點,並返回客戶端所需的確切資料。

由於GraphQL與ASGI相容,因此可以輕鬆地將其整合到FastAPI應用程式中。有很多Python庫可用於GraphQL。其中一些列在下面:

  • Strawberry

  • Ariadne

  • Tartiflette

  • Graphene

FastAPI的官方文件建議使用Strawberry庫,因為它的設計也基於型別註解(就像FastAPI本身一樣)。

為了將GraphQL與FastAPI應用整合,首先將Python類裝飾為Strawberry型別。

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

接下來,宣告一個包含返回Book物件的函式的Query類。

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

使用此Query類作為引數來獲取Strawberry.Schema物件。

schema = strawberry.Schema(query=Query)

然後宣告GraphQL類和FastAPI應用程式類的物件。

graphql_app = GraphQL(schema)
app = FastAPI()

最後,向FastAPI物件新增路由並執行伺服器。

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

在瀏覽器中訪問https://:8000/book。將開啟一個瀏覽器內GraphQL IDE。

FastAPI Using GraphQL

在註釋部分下方,使用Graphiql IDE的Explorer欄輸入以下查詢。執行查詢以在輸出窗格中顯示結果。

FastAPI Using GraphQL
廣告
© . All rights reserved.