You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI + Strawberry调用Rick&Morty API时出现'dict'无'name'属性错误

问题:FastAPI结合Strawberry GraphQL调用Rick&Morty API返回字段报错

我尝试使用FastAPI结合Strawberry GraphQL调用Rick&Morty的REST API获取角色字段,但始终遇到第一个字段的错误。

我的代码

from fastapi import FastAPI
import strawberry
from strawberry.fastapi import GraphQLRouter
import requests

@strawberry.type
class Character:
    id: int
    name: str
    status: str
    species: str

@strawberry.type
class Query:
    @strawberry.field
    def getIdent(self, ch: str) -> Character:
        url = f'https://rickandmortyapi.com/api/character/{ch}'
        return requests.get(url).json()

app = FastAPI()
schema = strawberry.Schema(Query)
graphql_app = GraphQLRouter(schema)
app.include_router(graphql_app, prefix="/graphql")

GraphQL查询

query MyQuery {
  getIdent(ch: "2") {
    name
    species
  }
}

错误信息

{
   "data": null,
   "errors": [
     {
       "message": "'dict' object has no attribute 'name'",
       "locations": [
          {
            "line": 3,
            "column": 5
          }
      ],
        "path": [
        "getIdent",
        "name"
      ]
     }
   ]
}

解决方案

报错原因很直接:你直接返回了requests.get(url).json()得到的字典对象,但Strawberry GraphQL需要的是你定义的Character类实例,而非字典。字典只能通过键访问(比如data["name"]),但Strawberry会尝试用属性访问的方式(比如obj.name)获取字段,因此触发报错。

修改getIdent方法,把字典数据转换成Character实例再返回:

@strawberry.type
class Query:
    @strawberry.field
    def getIdent(self, ch: str) -> Character:
        url = f'https://rickandmortyapi.com/api/character/{ch}'
        data = requests.get(url).json()
        # 将字典数据映射到Character类实例
        return Character(
            id=data["id"],
            name=data["name"],
            status=data["status"],
            species=data["species"]
        )

这样Strawberry就能正确解析Character实例的字段,返回你需要的数据了。

内容的提问来源于stack exchange,提问作者Cristoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:50:23