Skip to content

Instantly share code, notes, and snippets.

@ammarnajjar
Created April 21, 2020 00:08
Show Gist options
  • Save ammarnajjar/f72073a01c20a1d513e5fcca19766ef3 to your computer and use it in GitHub Desktop.
Save ammarnajjar/f72073a01c20a1d513e5fcca19766ef3 to your computer and use it in GitHub Desktop.
compare github API v3 (rest) VS v4 (grapghql)
import os
from gql import Client
from gql import gql
from gql.transport.requests import RequestsHTTPTransport
from typing import Any
from typing import Dict
class Gister:
def __init__(
self,
end_point: str = 'https://api.github.com/graphql',
user: str = 'ammarnajjar',
token_file: str = os.path.join(
os.getenv("HOME"),
'.config', 'gist', 'gist'
),
) -> None:
self.end_point = end_point
self.user = user
self.token_file = token_file
def _token(self) -> str:
with open(self.token_file, 'r') as fi:
return fi.read().rstrip()
def get_gists(self) -> Dict[str, Any]:
token = self._token()
sample_transport = RequestsHTTPTransport(
url=self.end_point,
use_json=True,
headers={
"Content-type": "application/json",
'Authorization': f'bearer {token}',
},
verify=True,
)
client = Client(
retries=3,
transport=sample_transport,
fetch_schema_from_transport=True,
)
query = gql(f"""
query getContinents
{{
user(login: "{self.user}") {{
gists(last: 3) {{
nodes {{
createdAt
name
description
files {{
name
}}
}}
}}
}}
}}
""")
return client.execute(query)
def main() -> None:
gister = Gister()
res = gister.get_gists()
print(res)
if __name__ == '__main__':
main()
import json
import os
import urllib.request
from typing import Any
from typing import Dict
class Gister:
def __init__(
self,
url='https://api.github.com',
user='ammarnajjar',
token_file=os.path.join(
os.getenv("HOME"),
'.config', 'gist', 'gist'
),
) -> None:
self.url = url
self.user = user
self.token_file = token_file
def _token(self) -> str:
with open(self.token_file, 'r') as fi:
return fi.read().rstrip()
def get_gists(self) -> Dict[str, Any]:
token = self._token()
url = f'{self.url}/users/{self.user}/gists'
headers = {
"Content-type": "application/json",
'Authorization': f'token {token}',
}
req = urllib.request.Request(url, headers=headers)
return json.loads(urllib.request.urlopen(req).read())
def main() -> None:
gister = Gister()
res = gister.get_gists()[:3]
print([x.get('files') for x in res])
if __name__ == '__main__':
main()
$ date
Tue Apr 21 02:07:37 CEST 2020
$ time python github_rest.py
real 0m0.788s
user 0m0.099s
sys 0m0.029s
$ time python github_graphql.py
real 0m3.597s
user 0m0.367s
sys 0m0.074s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment