Using API Data with TigerGraph

Why Does This Matter?

Agenda

Step 0: Set Up

!pip install pyTigerGraph

Step 1: Explore PokéAPI

Image for post

import requests
import json
import pyTigerGraph as tg
URL = "https://pokeapi.co/api/v2/pokemon/12/" # URLres = requests.get(url = URL).json() # Makes the GET Requestprint(json.dumps(res, indent = 2)) # Printing the Results
print(res["species"])print(res["types"])

Step 2: Create Graph in TigerGraph

conn = tg.TigerGraphConnection(host="https://DOMAIN.i.tgcloud.io", password="tigergraph", gsqlVersion="3.0.5", useCert=True)
# Sets up connection with GSQLprint(conn.gsql('ls', options=[]))# Create Edges (POKEMON_TYPE) and Vertices (Pokemon and Type)print(conn.gsql('''CREATE VERTEX Pokemon (PRIMARY_ID name STRING) WITH primary_id_as_attribute="true"CREATE VERTEX Type (PRIMARY_ID type STRING) WITH primary_id_as_attribute="true"CREATE UNDIRECTED EDGE POKEMON_TYPE (FROM Pokemon, TO Type)''', options=[]))
print(conn.gsql('''CREATE GRAPH pokemon(Pokemon, Type, POKEMON_TYPE)''', options=[])) # Create the Graph

Image for post

Step 3: Load Data from API

conn.graphname = "pokemon"conn.apiToken = conn.getToken(conn.createSecret())
URL = "https://pokeapi.co/api/v2/pokemon/12/" # URLres = requests.get(url = URL).json() # Makes the GET Requestprint(json.dumps(res, indent = 2)) # Printing the Results
conn.upsertVertex("Pokemon", res["species"]["name"], attributes={"name": res["species"]["name"] })
for ty in res["types"]:     conn.upsertVertex("Type", ty["type"]["name"], attributes={"type": ty["type"]["name"] })     conn.upsertEdge("Pokemon", res["species"]["name"], "POKEMON_TYPE", "Type", ty["type"]["name"])
for i in range(1,100): # You can change the number based on how many Pokémon you want to add    URL = f"https://pokeapi.co/api/v2/pokemon/{i}/" # URL    res = requests.get(url = URL).json() # We don't have any parameters.    conn.upsertVertex("Pokemon", res["species"]["name"], attributes={"name": res["species"]["name"] })    for ty in res["types"]:        conn.upsertVertex("Type", ty["type"]["name"], attributes={"type": ty["type"]["name"] })        conn.upsertEdge("Pokemon", res["species"]["name"], "POKEMON_TYPE", "Type", ty["type"]["name"])     print("Added " + res["species"]["name"])

Image for post

Step 4: Your Turn!

Resources

You Might Also Like