简体   繁体   中英

How can GitHub's GraphQL API can be consumed from Java?

I'd like to consume GitHub's GraphQL API from Java and after extensive searching I was not able to find a library or other solution which lets me do this in an easy to use way.

The official docs do not detail how this can be done either.

How can I consume GitHub's v4 API? I'd like to generate code based on the API itself so I can use it in a programmatic way.

I would suggest you try out open source Insomnia. It gives you the ability to automatically generate Java code from your GraphQL queries for the OkHttp library to use.

For example:

The following graphQL query...

query GetIssues($client: String!
                             ) {
  organization(login: $client) {
    name
    repositories(last: 10) {
      edges {
        cursor
        node {
          name
          url
          description
        }
      }
    }
  }
}

...will generate the following Java snippet...

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/graphql");
RequestBody body = RequestBody.create(mediaType, "{\"query\":\"query GetIssues($client: String!) {\\n  organization(login: $client) {\\n    name\\n    repositories(last: 10) {\\n      edges {\\n        cursor\\n        node {\\n          name\\n          url\\n          description\\n        }\\n      }\\n    }\\n  }\\n}\\n\",\"variables\":{\"client\":\"AniTrend\"},\"operationName\":\"GetIssues\"}");
Request request = new Request.Builder()
  .url("https://api.github.com/graphql")
  .post(body)
  .addHeader("authorization", "Bearer YOU_BEARER_AUTH_HERE")
  .build();

Response response = client.newCall(request).execute();

Then if you use what you know about GraphQL variables in the queries and mate that to what you know about Java variables, you should then be able to modify the RequestBody strings. It's a simple and dirty solution that has loads of room for improvement, something I am exploring currently as well. I'll revisit this as I develop a more robust solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM