在引用此guide之后,我需要使用graphql
来访问github curl
以进行测试。我尝试了这个简单的命令
curl -i -H "Authorization: bearer myGithubAccessToken" -X POST -d '{"query": "query {repository(owner: "wso2", name: "product-is") {description}}"}' https://api.github.com/graphql
但它给了我
解析JSON的问题
我做错了什么。我花了将近2个小时试图弄清楚它并尝试了不同的例子,但没有一个能够奏效。能帮助我解决这个问题吗?
答案 0 :(得分:10)
您只需要将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
答案 1 :(得分:3)
如果您希望查询保持多行美观,您可以这样做:
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 onliner, without newlines
curl -i -H 'Content-Type: application/json' \
-H "Authorization: bearer ........." \
-X POST -d "{ \"query\": \"$script\"}" https://api.github.com/graphql
答案 2 :(得分:1)
因为这是'graphql curl'的第一次命中,这里有一个简单的例子:
$ curl \
--request POST \
--header 'Content-Type: application/json' \
--data '{"query": "query { fish(key:\"838\") { name } }"}' \
http://localhost:4001
{"data":{"fish":{"name":"plecy"}}}
答案 3 :(得分:0)
我建议将graphql存储在一个文件中,并将用于处理它的脚本存储在一个单独的文件中,然后在提示符下将两者合并。
这使您可以在自己喜欢的编辑器中编辑examplequery.gql
时使用graphql syntax highlighting plugins和graphql pretty printers。同时还保留了在您的graphql-fu无法胜任任务的情况下使用cli工具包的能力。
用法:
❯ ./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
}
}
}
}
}
}