python关于graphql接口的调用

仲孙兴旺
2023-12-01

1. Query

query = 'query MyQuery {Book(id: 1) {id, name, ver}}'
        payload_query = {'query': query}
        response_query = requests.post('http://127.0.0.1:8001/graphql', headers=headers,
                                       data=json.dumps(payload_query))
        self.assertTrue(response_query.status_code == requests.codes.ok)
        content_json_data_query = json.loads(response_query.content)
        # 获取版本号
        ver = jsonpath(content_json_data_query, '$.data.Book.ver')[0]

2. Mutation

mutation = f'mutation MyMutation {{updateMdtBook(id: 1, ver: {ver}, values: {{code: "ABC"}}) ' \
                   f'{{code}}}} '
        payload_mutation = {'query': mutation}
        # 将code与Book关联
        response_mutation = requests.post('http://127.0.0.1:8001/graphql', headers=headers,
                                          data=json.dumps(payload_mutation))
        self.assertTrue(response_mutation.status_code == requests.codes.ok)
        content_json_data_mutation = json.loads(response_mutation.content)
        # 数据不存在时,会返回False,确保数据存在,不能等于False
        self.assertTrue(jsonpath(content_json_data_mutation, '$.data.updateBook.code'))
        self.assertEqual('ABC', jsonpath(content_json_data_mutation, '$.data.updateBook.code')[0])

 

 类似资料: