Python GraphQL API调用 [英] Python GraphQL API call

查看:67
本文介绍了Python GraphQL API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习如何使用python,并且我在graphQL api调用上遇到了一些麻烦.

I've recently started learning how to use python and i'm having some trouble with a graphQL api call.

我正在尝试建立一个循环以使用分页获取所有信息,而我的第一个请求运行得很好.

I'm trying to set up a loop to grab all the information using pagination, and my first request is working just fine.

values = """
      {"query" : "{organizations(ids:) {pipes {id name phases {id name cards_count cards(first:30){pageInfo{endCursor hasNextPage} edges {node {id title current_phase{name} assignees {name} due_date createdAt finished_at fields{name value filled_at updated_at} } } } } }}}"}
    """

但是使用结束游标作为变量的第二次调用对我不起作用.我认为这是因为我不了解如何正确地转义变量的字符串.但是对于我的一生,我无法理解应该怎么做.

but the second call using the end cursor as a variable isn't working for me. I assume that it's because i'm not understanding how to properly escape the string of the variable. But for the life of me I'm unable to understand how it should be done.

到目前为止,这就是我想要的...

Here's what I've got for it so far...

values = """
      {"query" : "{phase(id: """ + phaseID+ """ ){id name cards_count cards(first:30, after:"""\" + pointer + "\"""){pageInfo{endCursor hasNextPage} edges {node {id title assignees {name} due_date createdAt finished_at fields{name value datetime_value updated_at phase_field { id label }  } } } } } }"}
        """ 

第二个循环时,它只会返回一个400错误的请求.

the second one as it loops just returns a 400 bad request.

任何帮助将不胜感激.

推荐答案

一般来说,您应该避免使用这样的字符串操作来建立查询.

As a general rule you should avoid building up queries using string manipulation like this.

在GraphQL查询本身中,GraphQL允许变量可以作为查询中的占位符对于值,您将在以后插入.您需要在查询顶部声明变量,然后可以在查询中的任何位置引用它们.没有JSON包装器的查询本身看起来像

In the GraphQL query itself, GraphQL allows variables that can be placeholders in the query for values you will plug in later. You need to declare the variables at the top of the query, and then can reference them anywhere inside the query. The query itself, without the JSON wrapper, would look something like

query = """
  query MoreCards($phase: ID!, $cursor: String) {
    phase(id: $phase) {
      id, name, cards_count
      cards(first: 30, after: $cursor) {
        ... CardConnectionData
      }
    }
  }
"""

要实际提供变量值,它们将作为普通字典传递

To actually supply the variable values, they get passed as an ordinary dictionary

variables = {
  "phase": phaseID,
  "cursor": pointer
}

实际的请求正文为一个简单的JSON结构.您也可以将其构造为字典:

The actual request body is a straightforward JSON structure. You can construct this as a dictionary too:

body = {
  "query": query,
  "variables": variables
}

现在,您可以使用标准的 json 模块以将其格式化为字符串

Now you can use the standard json module to format it to a string

print(json.dumps(body))

或将其传递给

or pass it along to something like the requests package that can directly accept the object and encode it for you.

这篇关于Python GraphQL API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆