Remember to invoke the GitHub API via C # using GRAPHQL

Source: Internet
Author: User
Tags local time

    • What is GRAPHQL?
    • How to use graphql under. Net
    • Invoke the GitHub API using GRAPHQL
    • Conclusion

First, what is GRAPHQL?

Recently in the toss using GitHub API to do a small program practice practiced hand, this article is recorded in this process.

Take a look at GRAPHQL's grammatical style and feel it:

Query {  Repository (owner:"Octocat", Name: "Hello-world") {      id  }}

This is one of the simplest examples of the application, which is equivalent to http://graphqlapi.xxx.com/query/repository?owner=octocat&name=Hello-World in effect, and returns the format of the content:

{  "data"    : {"Repository":{      "id": "mdewoljlcg9zaxrvcnkxmjk2mjy5"    }  }}

Then look at a slightly more complex query method:

Query {  Repository (owner:"Octocat", Name: "Hello-world") {    issues (last: states:closed) {      edges {        Node {          title          URL          labels (first:5) {            edges {              Node {                name              }            }   }}}}

This is a multi-level object nested query, where it does not continue to unfold. There will be a little explanation on Egde and node below. Graphql interested in a more in-depth understanding of the study can be self-learning, I am just getting started, do not pit everyone:), the official website is http://graphql.org/(this may not open, you can open the address of the domestic http:/ graphql.cn), Facebook publishes a specification in http://facebook.github.io/graphql/October2016/.

GRAPHQL is both a query language for the API and a runtime that satisfies your data query. GRAPHQL provides a complete, easy-to-understand description of the data in your API, allowing the client to get exactly the data it needs, without any redundancy, making it easier for the API to evolve over time, and to build powerful developer tools.

Ii. How to apply graphql under. Net

Since I need to do a timed task to pull the data on GitHub to local time, it's natural to choose the back-end approach. Find the GRAPHQL client under. NET, with this graphql-client. The code is as follows:

varHerorequest =Newgraphqlrequest {Query=GRAPHQL//fill in the contents of the query here. };varGraphqlclient =NewGraphqlclient ("https://api.github.com/graphql"); GraphQLClient.DefaultRequestHeaders.UserAgent.Add ( new Productinfoheadervalue ("Safari", "537.36"));   
Above this line is very key, useragent must write, otherwise will appear 403 error, spent a long time to find this problem.
GRAPHQLCLIENT.DEFAULTREQUESTHEADERS.ADD ("Authorization","bearer token "); The token here is a placeholder that actually needs to be generated on GitHub. varGraphqlresponse = Graphqlclient.postasync (herorequest). Result;

For token generation and some other environmental preparations, there is a detailed description on GitHub, see: https://developer.github.com/v4/guides/forming-calls/# Authenticating-with-graphql.

Important thing to say 3 times:useragent must write!!  useragent must be written!! useragent must be written!!

Iii. using GRAPHQL to invoke the GitHub API

GitHub provides APIs and related documentation on the directory tree to the right of https://developer.github.com/v4/, this time I need to pull a lot of GitHub's repository library, so I used the search interface (but strangely, This interface is not listed in the document and does not know why. It is recommended that you test and validate your GitHub-provided explorer first, and OK to write the code into the actual project.

Then, the author in the realization of their own functions needed to learn 2 concepts, in order to carry out the following work normally. The first is the edge and node concept, the edge can be understood as a paging object, in addition to the actual data there is a cursor (the unique identity of each returned data, if you want to page the data, with the before and after keyword to use) field, The actual data is represented by node.

In addition, GRAPHQL is strongly typed , so when the search returned by the author is not a definite data object, it is necessary to get the actual object through the __typename field under node. The code is as follows:

Query {  search (query:"language:c#", Type:repository,first:1) {    edges{      cursor,      node{        __typename      }   }}}

The resulting results are:

{  "data"    : {"Search"      : {"Edges": [        {          "cursor": " Y3vyc29yoje= ",          " Node ": {            " __typename ":"Repository"          }        }      ]    }  }}

After the actual data object is repository, what fields are available for the object by looking at the GitHub API's documentation and selecting the required fields from it. This is one of the natural advantages of GRAPHQL's design, available on Demand . It is necessary to introduce a new concept fragment in the next application, which can be understood as a template to indicate to the server the data fields that need to be obtained. The code is as follows:

fragment repfragment on Repository {  name,  forkcount,  url,  createdat,  Updatedat,  licenseinfo{  //Object nesting    nickname    //licenseinfo nickname Field  },  stargazers{   //Object Nesting    TotalCount  //stargazers totalcount field  }}query {  search (query:"language:c#", Type:repository, first:100) {    edges{      cursor,      node{        __typename        ... repfragment  }}} 

Okay, so I'll get the results I need.

The following is attached to the author's demo:https://github.com/zacharyfan/githubranking, wherein the token in the configuration file can be replaced by themselves.

Iv. Conclusion

Finally, with the advent of GRAPHQL, the main scenario is to empower the front-end developers to freely organize and customize the request data. This is a front-end separation of the boundaries of the frame, so directly at the front end through the GRAPHQL access to the backend data is a more respected way of personal. At present the front-end very fiery graphql frame also many, the mainstream is below 2: Apollo (https://github.com/apollographql/apollo-client), relay (https:// Github.com/facebook/relay).

GRAPHQL although good, but to really in large and medium-sized projects to use GRAPHQL, there are a lot of difficulties, the server needs to support the GRAPHQL specification format for data output, I think the cost is not small. Even with an intermediate layer, problems such as distribution, aggregation, and performance need to be addressed.

Zachary_fan
Source: http://www.cnblogs.com/Zachary-Fan/p/CsharpGraphql.html

If you want to get a personal self-written article in time to push the message, Welcome to scan the following QR code ~.

Remember to invoke the GitHub API via C # using GRAPHQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.