跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

SymfonyGraphQLAPI_使用ApiPlatform实现【介绍】

ApiPlatform 的 GraphQL 入口默认未启用,需手动配置 graphql: true、安装 webonyx/graphql-php、确保 symfony/serializer ≥ 6.4,并在实体中显式声明 graphql 查询/突变及字段可读写属性。 ApiPlatform 的
GraphQL
入口默认不启用 装完 ApiPlatform,默认只有 REST,
GraphQL
端点(如
/api/graphql
)根本不存在,访问直接 404。这不是配置漏了,是它压根没开——得手动激活。 检查
config/packages/api_platform.yaml
,确保有
graphql: true
(不是
enabled: true
,那是旧版写法) 确认已安装
webonyx/graphql-php
:运行
composer require webonyx/graphql-php
,ApiPlatform 3.x 不再自动带它 若用 Symfony 6.4+,还要确认
symfony/serializer
版本 ≥ 6.4,否则
GraphQL
类型推导会报
Cannot autowire service "ApiPlatform\GraphQl\Type\Definition\TypeBuilder"
Query
和
Mutation
类型没生成?看实体注解和资源配置 ApiPlatform 不靠 Doctrine 注解自动生成 GraphQL Schema,而是依赖资源(Resource)是否被显式暴露、以及字段是否可读/可写。哪怕实体加了
@ApiResource
,缺关键配置照样不出字段。 实体类必须有
@ApiResource(graphql: {"query": true, "mutation": true})
,只写
graphql: true
不生效 字段级控制靠
@ApiProperty(readable: true, writable: true)
,
readonly
或
writeonly
会直接从 Schema 消失 关联字段(如
$author
)默认不嵌套展开,要加
graphQlRead: true
才进 Query,加
graphQlWrite: true
才进 Mutation 执行
graphql
查询返回空对象或
"message": "Internal server error"
常见于类型映射失败或序列化器冲突,尤其在用
DateTimeInterface
、自定义 DTO 或继承实体时。错误日志往往藏在 Symfony profiler 的「Logs」里,而不是响应体中。 打开
debug:router
确认
api_graphql_entrypoint
路由存在且 method 是
POST
在
config/packages/api_platform.yaml
加
enable_profiler: true
,然后用 GraphiQL 访问
/api/graphql?debug
查具体异常堆栈 避免在实体中用
DateTime
直接作为属性类型;改用
DateTimeInterface
并配
@ApiProperty(schema: {"type": "string", "format": "date-time"})
DTO 作
input
时,必须实现
__construct()
且参数全可选,否则
GraphQL
解析器会因构造失败而静默返回空 Symfony 事件监听器在
GraphQL
请求中不触发 因为 ApiPlatform 的 GraphQL 层绕过了传统控制器生命周期,
kernel.controller
、
kernel.view
这些事件默认不发。想插手数据读写,得换地方挂钩子。 读操作(Query)用
ApiPlatform\GraphQl\Resolver\QueryItemResolverInterface
或
QueryCollectionResolverInterface
实现自定义解析器 写操作(Mutation)改写
ApiPlatform\GraphQl\Resolver\MutationResolverInterface
,在
resolve()
里手动调用你的业务逻辑 别试图在
onKernelRequest
里判断
$request->getRequestFormat() === 'graphql'
—— 它永远是
html
或空,GraphQL 请求的 format 是隐式的 GraphQL 的 Schema 构建发生在容器编译期,不是请求时。改一个
@ApiProperty
注解后必须清缓存(
cache:clear
),否则开发环境也看不到变化。

相关文章