GraphQL复杂cURL查询(GitHub API v4)

时间:2018-03-13 11:40:47

标签: json curl github graphql github-api

我正在尝试在JS应用程序中对GitHub v4 API执行GraphQL查询,但我遇到了“JSON问题”错误。 所以我试图用cURL来做,但它似乎有一个我看不到的问题。


    curl -H "Authorization: token bearer" -H  "Content-Type:application/json" -X POST -d '{ "query": "query {
      viewer {                                                             
        watching(first: 3, orderBy: {field: UPDATED_AT, direction: DESC}) {
          nodes {                                                                                            
            refs(refPrefix: \"refs/heads/\", orderBy: {direction: DESC, field: TAG_COMMIT_DATE}, last: 100) {
              nodes {   
                target {         
                  ... on Commit {       
                    history(first: 10) {
                      ...CommitFragment
                    }
                  }
                }
              }
            }
          }
        }
      }          
      rateLimit {
        limit
        cost     
        remaining
        resetAt
      }
    }

    fragment CommitFragment on CommitHistoryConnection {
      nodes {  
        message 
        author {
          name               
          avatarUrl(size: 30)
        }
      }
    }                                  

我想提一下,该请求正在github.com/v4/explorer/网站上运行。 我已经逃脱了报价......

1 个答案:

答案 0 :(得分:1)

问题是查询是JSON字符串化的,在您的请求中,您在JSON字符串字段query中添加了不允许的新行:

curl -H "Authorization: token YOUR_TOKEN" \
     -H  "Content-Type:application/json" \
     -d '{ 
          "query": "{ viewer { watching(first: 3, orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { refs(refPrefix: \"refs/heads/\", orderBy: {direction: DESC, field: TAG_COMMIT_DATE}, last: 100) { nodes { target { ... on Commit { history(first: 10) { ...CommitFragment } }}}}}}} rateLimit { limit cost remaining resetAt}}fragment CommitFragment on CommitHistoryConnection { nodes { message author { name avatarUrl(size: 30) } } }"
      }' https://api.github.com/graphql

如果使用Javascript,则使用XMLHttpRequest

var http = new XMLHttpRequest();
var url = "https://api.github.com/graphql";
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Authorization", "token YOUR_TOKEN");

http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}

http.send(JSON.stringify({
    "query": '{ viewer { watching(first: 3, orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { refs(refPrefix: "refs/heads/", orderBy: {direction: DESC, field: TAG_COMMIT_DATE}, last: 100) { nodes { target { ... on Commit { history(first: 10) { ...CommitFragment } }}}}}}} rateLimit { limit cost remaining resetAt}}fragment CommitFragment on CommitHistoryConnection { nodes { message author { name avatarUrl(size: 30) } } }'
}));

您还可以使用apollo-clientgraphql.js

查找示例