在 Python 中使用 GraphQL 查询新遗物

问题描述 投票:0回答:1

我刚刚开始将 GraphQL 与 New Relic 结合使用,但在尝试将变量传递给 GraphQL 查询时遇到了麻烦。 我需要根据 NR Synthetics 监视器的名称检索 GUID,为此我考虑搜索实体,然后从查询响应中获取 guid。 这是我包含查询的代码:

    query = '''
    query($query: String!) {
      actor {
        entitySearch(query: $query) {
          results {
            entities {
              guid
            }
          }
        }
      }
      variables { query: "name LIKE \u0027MYMONITORNAME\u0027" }
    }'''

然后我调用 NR API:

    my_response = requests.get(
    url=my_url,
    headers=header,
    json={"query": query}
)

我得到了这个:

{'errors': [{'locations': [{'column': 30, 'line': 12}], 'message': 'syntax error before: "\\"name LIKE \'MYMONITORNAME\'\\""'}]}

我尝试了很多转义序列、双引号/单引号/无引号组合,但似乎无法确定正确的格式。 任何指导将不胜感激。

提前致谢, 塞巴斯蒂安

python rest graphql newrelic
1个回答
0
投票

我将把它留在这里,以防对其他人有帮助。
这太复杂了,但这就是我使用 API 的方法

my_account_id = "ACCOUNT_ID" # looks like "1234567890"
my_graph_api_key = "API_KEY" # looks like "NRAK-XYZ12345678901234567890"

nrql = """
SELECT count(*) 
FROM Log 
WHERE allColumnSearch('thing I want to count', insensitive: true) 
SINCE 10 minutes ago
"""

graph_query = """{
    actor {
        account(id: %s) {
            nrql(query: \"%s\") {
                results
            }
        }
    }
}""" % (my_account_id, nrql)

url = "https://api.newrelic.com/graphql"
headers = {
    "Content-Type": "application/json",
    "API-Key": my_graph_api_key,
}
payload = json.dumps({"query": graph_query})
response = requests.request("POST", url, headers=headers, data=payload)
print(response.json())
© www.soinside.com 2019 - 2024. All rights reserved.