如何使用curl访问Github GraphQL API

42

参考了这篇指南后,我需要使用curl来访问Github的graphql进行测试。我尝试了这个简单的命令

curl -i -H "Authorization: bearer myGithubAccessToken" -X POST -d '{"query": "query {repository(owner: "wso2", name: "product-is") {description}}"}' https://api.github.com/graphql

但它给了我

JSON解析问题

我做错了什么?我花了近两个小时的时间尝试弄清楚,尝试了不同的示例,但都没有成功。您能否好心帮我解决这个问题。

4个回答

47

您只需要转义JSON中作为查询的双引号即可

$ curl -i -H 'Content-Type: application/json' -H "Authorization: bearer myGithubAccessToken" -X POST -d '{"query": "query {repository(owner: \"wso2\", name: \"product-is\") {description}}"}' https://api.github.com/graphql


4
为了访问我自己的基于Django/Graphene的API,我尝试得出这个答案;为此,我需要额外添加一个"-H 'Content-Type: application/json'"。 - Silly Freak

34

如果您希望您的查询保持良好的多行格式,您可以这样做:

script='query {
  repositoryOwner(login:\"danbst\") {
    repositories(first: 100) {
      edges {
        node {
          nameWithOwner
          pullRequests(last: 100, states: OPEN) {
            edges {
              node {
                title
                url
                author {
                  login
                }
                labels(first: 20) {
                  edges {
                    node {
                      name
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}'
script="$(echo $script)"   # the query should be a one-liner, without newlines

curl -i -H 'Content-Type: application/json' \
   -H "Authorization: bearer ........." \
   -X POST -d "{ \"query\": \"$script\"}" https://api.github.com/graphql

为什么需要 script="$(echo $script)" - dkrikun
@dkrikun 为了去除换行符。在撰写本文时,请求正文中不允许出现换行符。sed 解决方案同样适用于此。 - danbst
1
看起来现在允许换行符,我在我的JSON中使用了它们(类似于资源管理器使用的结构),只要引号被转义,它就完美地工作。 - Lorna Mitchell
我更新了解决方案,避免转义引号,使用sed来完成。 - Denis Rouzaud
8
你可以使用curl -H "Authorization: token YOUR_GITHUB_TOKEN" -X POST https://api.github.com/graphql --data @gql.json 命令,并创建一个名为 gql.json 的文件,将你的对象放置其中。你可以使用你喜欢的代码编辑器和 JSON 格式化工具轻松地对其进行更改等操作。 - Jerry Green
script="$(echo $script)" 这种写法过于晦涩,而且 shellcheck 和其他工具会对裸露的 $script 抱怨不已,因为它没有双引号。我使用 script=$(echo "$script" | tr -d '\n'),这样写更清晰明了,表达了它的用途。 - APerson

7

因为这是“graphql curl”搜索结果的首个命中,所以在此提供一个简单示例:

$ curl \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{"query": "query { fish(key:\"838\") { name } }"}' \
  http://localhost:4001

{"data":{"fish":{"name":"plecy"}}}

6
我建议将graphql存储在一个文件中,并在另一个文件中编写处理脚本,然后在提示符处将两个文件组合起来。
这样,在您喜欢的编辑器中编辑examplequery.gql时,您可以使用 graphql语法突出显示插件 graphql漂亮打印机。同时,还保留了使用cli工具包的能力,以处理graphql-fu无法胜任的情况。 用法:
❯ ./ghgql.sh examplequery.gql

    {"data":{"user":{"repositories":{"nodes":[{"name":"firstrepo","languages":{"nodes":[]}},{"name":"secondrepo","languages":{"nodes":[{"name":"Shell"},{"name":"Vim script"}]}},{"name":"thirdrepo","languages":{"nodes":[{"name":"TeX"}]}}]}}}}

❯ ./ghgql.sh examplequery.gql \
    | jq -c '.data.user.repositories.nodes | to_entries | .[]' \
    | grep 'TeX' \
    | jq -r '.value.name'

    thirdrepo

ghgql.sh

#!/usr/bin/env bash

if [ ! -f $1 ] || [ $# -ne 1 ]
then
    echo Queries the github graphql API
    echo "Usage:"
    echo
    echo "$0 somefile.gql"
fi

# read the gql query from the file named in the argument
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
TOKEN=$(cat $DIR/token)
QUERY=$(jq -n \
           --arg q "$(cat $1 | tr -d '\n')" \
           '{ query: $q }')

# do the query
curl -s -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: bearer $TOKEN" \
  --data "$QUERY" \
  https://api.github.com/graphql

examplequery.gql

{
  user(login: "MatrixManAtYrService") {
    repositories(first: 3) {
      nodes {
        name
        languages(first: 3) {
          nodes {
            name
          }
        }
      }
    }
  }
}

我将bearer更改为我的GitHub用户名,并在名为token的文件中放置了来自GitHub的PAT,该文件位于工作目录中,但仍然收到以下错误信息:{ "message": "This endpoint requires you to be authenticated.", "documentation_url": "https://docs.github.com/graphql/guides/forming-calls-with-graphql#authenticating-with-graphql" } 我是否没有理解如何传递token的方式? - robartsd
@robartsd,bearer这个词不是GitHub用户的名称。所以你应该保留它为bearer。我认为它表示一个GitHub个人访问令牌即将到来。一个可行的语法可能是:-H "Authorization: bearer somegithubpersonalaccesstoken" \ - a.t.
谢谢!在我看来,这是一个被低估的答案。这样很容易专注于GraphQL查询本身,而不会与JSON格式混淆。 - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接