如何在Api Platform v3.1(Symfony6)中测试GraphQL端点并传递查询?
解决Api Platform v3.1 + Symfony 6 GraphQL测试查询传递错误
你的代码存在两个核心问题,导致了"GraphQL query is not valid"错误:
- 错误使用
GET请求,GraphQL官方及Api Platform均推荐/要求用POST请求处理查询与变更 - 查询参数的传递格式不符合规范,未正确将GraphQL查询放入请求体中
修正后的测试代码
final class Test extends ApiTestCase { public function setUp(): void { parent::setUp(); } public function testProfile(): void { $client = self::createClient(); $fixtures = $this->databaseTool ->loadFixtures([ UserTestFixtures::class ]) ->getReferenceRepository(); $user = $fixtures->getReference('user_operator'); $token = $this->getToken([ 'username' => $user->getEmail(), 'password' => 'S3cret' ]); // 使用POST请求发送GraphQL查询 $response = $client->request('POST', '/api/graphql', [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token ], // 将查询以JSON格式放入请求体 'json' => [ 'query' => 'query getProfile { profileUser { id firstName lastName email } }' ] ]); // 可选:验证响应状态与返回数据 $this->assertResponseIsSuccessful(); $data = $response->toArray(); $this->assertEquals($user->getEmail(), $data['data']['profileUser']['email']); } }
关键说明
- 请求方法:必须使用
POST,Api Platform的GraphQL端点默认仅接受POST请求处理查询和变更操作 - 请求体传递:利用Symfony测试客户端的
json选项传递数组,客户端会自动编码为JSON字符串并设置正确的请求头 - 带变量的查询:如果需要传递动态变量,可以添加
variables字段,示例如下:'json' => [ 'query' => 'query getProfile($id: ID!) { profileUser(id: $id) { id firstName } }', 'variables' => ['id' => $user->getId()] ]
内容的提问来源于stack exchange,提问作者patHub
相关产品推荐
相关产品推荐

