Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样用 Strawberry 给 FastAPI 接入 GraphQL?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

用 Strawberry 定义 GraphQL 的类型与查询,创建 Schema,再把 GraphQLRouter 注册到 FastAPI。客户端在这个入口提交查询,由 resolver 取得字段值。

讲清原理

GraphQL 的灵活性也可能放大数据库访问量。授权可进入上下文与 resolver,查询复杂度、批量数据和错误格式根据服务需求约束。

例子与易错点

示例注册一条只读查询,并断言返回结构。GraphQL 查询能成功运行不代表权限和复杂查询已经覆盖。

import strawberry
from fastapi import FastAPI
from fastapi.testclient import TestClient
from strawberry.fastapi import GraphQLRouter

@strawberry.type
class Query:
    @strawberry.field
    def item_title(self, code: str) -> str | None:
        return {"T001": "Tea"}.get(code)

app = FastAPI()
app.include_router(GraphQLRouter(strawberry.Schema(query=Query), graphql_ide=None),
                   prefix="/graphql")

with TestClient(app) as client:
    reply = client.post(
        "/graphql",
        json={"query": "query ($code: String!) { itemTitle(code: $code) }",
              "variables": {"code": "T001"}},
    )
    assert reply.status_code == 200
    assert reply.json() == {"data": {"itemTitle": "Tea"}}
print(reply.json()["data"]["itemTitle"])

相关题:第 69 题、第 70 题、第 73 题、第 88 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。