TigerGraph Universal Middle Tier for Frontend Client with FastAPI & pyTigerGraph

Using FastAPI and pyTigerGraph to Interact with a Healthcare Graph to Create UIs

Shreya Chaudhary
Towards Data Science

--

Overview

Why?

Right now, I’m working on a project to create a Flutter app with a TigerGraph backend. However, this raises the question of how exactly should Flutter “talk” to our graph database? One of the best and most secure ways of doing this is through an Application Programming Interface (API), specifically FastAPI in this case, a modern, high-performance web framework for building APIs with Python. This way, our Flutter app can send a request to FastAPI which will send that request to TigerGraph and return the needed data.

This method can be used not only for Flutter but for in essence any frontend that you’d like to use with TigerGraph. So let’s jump into how to create this!

Itinerary

  1. Overview
  2. Set up your Virtual Environment
  3. Set up FastAPI
  4. Set up TigerGraph
  5. Write Query Functions
  6. Congrats, Resources, and Next Steps

Tools Used

In this blog, we’ll be using…

Acknowledgement

Huge thank you to Advit Deepak, Kevin Hsu, Ramki Pitchala, Mohamed Zrouga, and Jon Herke for either helping with the project, pointing us in the right direction, and/or mentoring us!

Part I: Set up your Virtual Environment

Step I: Create your Directory

To start off, we’ll create a virtual environment. A virtual environment is a tool which keeps different dependencies of different projects isolated. In essence, using this, we won’t have to pip install all of the packages on our main computer; rather, all the packages we’ll use will be in our virtual environment.

First, start off by creating your directory to house the project then enter that directory.

mkdir TGFlutter
cd TGFlutter

Step II: Create your Virtual Environment

Awesome! Now, using Python, we can create a virtual environment using venv and Python. To do this, simply use the following command:

python3 -m venv venv

This creates a folder called “venv” in our directory. We can then activate this virtual environment using:

source venv/bin/activate

After running this, you should see a (venv) in front of your terminal.

After creating your virtual environment and activating it, you’ll see (venv) in front of your terminal

Step III: Install Packages

For this project, we’ll be using pyTigerGraph and Fast PI. FastAPI also uses a library called uvicorn, so we’ll install that as well.

pip install pyTigerGraph fastapi uvicorn

Perfect! After running this, we should be ready to go!

Part II: Set up FastAPI

Step I: Create a Basic API

Now, let’s create our first basic API. First, let’s create a file called “main.py.”

touch main.py

Click into it, and then use the code from the FastAPI website in that file.

from typing import Optional  
from fastapi import FastAPI
app = FastAPI() @app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}

Step II: Run the API

Save main.py then run it with the following command:

uvicorn main:app --reload

Here, we’re using uvicorn to run our file. The filename is main and the --reload has the server automatically reload after we save new changes to the file.

Step III: Explore the Custom Endpoints

Open a browser to the page https://127.0.0.1:8000. There, you’ll find the {“Hello”: “World”} from the first function.

Opened root in Chrome tab
@app.get("/") 
def read_root():
return {"Hello": "World"}

Now, let’s go to https://127.0.0.1:8000/items/1. That will result in {“item_id”:1,”q”:null}. The “item_id” is the parameter we passed into it (the /1), but we didn’t pass a q in this case.

Opened items endpoint with the id as 1

Let’s give q a value by going to https://127.0.0.1:8000/items/1?q=test.

Opened items endpoint with id as 1 and q as test

Perfect! Here, we passed the optional parameter q as test for the items endpoint.

@app.get("/items/{item_id}") 
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}

Step IV: Explore the Prebuilt Endpoints

Finally, FastAPI has a few prebuilt endpoints, specifically for creating documentation. First, if you go to http://127.0.0.1:8000/docs, you’ll find interactive documentation for the endpoints we created.

FastAPI docs

Not a fan of that style? If you go to http://127.0.0.1:8000/redoc, you’ll find a different style of documentation.

FastAPI redoc

And with that, let’s now start up the TigerGraph server to integrate pyTigerGraph to our endpoints.

If you want to learn more about FastAPI, check out its docs.

Part III: Set up TigerGraph

Step I: Create your Solution

Navigate to TigerGraph Cloud and create an account if you haven’t already.

Go to https://tgcloud.io/

Once logged in, navigate to the “My Solutions” tab. Next, press the blue “Create Solution” button.

Go to “My Solutions” then press the blue “Create Solution” button

For this example, we’ll be using Healthcare Graph (Drug Interaction/FAERS) starter kit. To select it, either scroll down or select the “Healthcare” category and click on the FAERS option. Once it’s selected, press “Next.”

Select “Healthcare” then click the second option (FAERS)

On the next page, don’t change anything, scroll down, and press “Next.”

Don’t change anything and press “Next”

Customize the third page to best describe your graph. Here, keep note of your password and subdomain, as we’ll be using this in pyTigerGraph. Press next.

Note: Write down your subdomain and password!

Enter in the appropriate information for your solution

On the final page, review that everything looks good, then press “Submit.”

Review everything then press “Submit”

Note: This may take a few minutes.

Once the dot by your solution is green and says “Ready,” then you’re ready to move on to the next step.

Wait till “Status” is “Ready”

Step II: Prepare your Solution

Now, let’s install our data and queries in preparation in the solution. To do this, open GraphStudio by going to the four squares under “Actions” and pressing “GraphStudio” from the dropdown.

In the tab that opens, click “Global View” in the top left corner then select “faers” from the dropdown to enter the faers graph.

First, we’ll load the data. To do this, click the “Load Data” tab then press the play button with the hover value of “Start/Resume loading.”

Load in the data

In the pop-up, press continue, then your data with start loading!

Press “Continue” to load the data

Perfect! Next, we’ll install the queries. To do this, go to the “Write Queries” tab and press the box with an up arrow.

Install the queries

Once again, in the popup, press “Install.” And after that, the queries will start installing!

Install all the queries

Wait till all the queries are install and the data is loaded, then continue to the next step!

If you want to learn more about TigerGraph Cloud, check out this blog.

Part IV: Integrate pyTigerGraph with FastAPI

Step I: Connect to your TigerGraph Cloud Solution

Perfect! Now we’re ready to integrate pyTigerGraph into our API. Open main.py in your editor of choice and import pyTigerGraph.

import pyTigerGraph as tg

Next, create a connection to your TigerGraph Cloud server.

conn = tg.TigerGraphConnection(host="https://faers.i.tgcloud.io/", password = "tigergraph", graphname="faers")conn.apiToken = conn.getToken(conn.createSecret())

Alternatively, to make this safer, create a configs.py file and import the credentials from there.

touch configs.py

In configs.py:

HOST = "https://faers.i.tgcloud.io/"
PASSWORD = "tigergraph"

Then, in main.py:

import configsconn = tg.TigerGraphConnection(host=configs.HOST, password = configs.PASSWORD, graphname="faers")conn.apiToken = conn.getToken(conn.createSecret())

If this runs successfully, then you’re connected to TigerGraph Cloud! Congrats!

Step II: Create Query Endpoints

Let’s first run TigerGraph queries with FastAPI, starting with mostReportedDrugsForCompany_v2.

@app.get("/mostReportedDrugsForCompany")def read_drugs(companyName: Optional[str] = "PFIZER", k: Optional[int] = 5, role: Optional[str] = "PS"):   try:      return conn.runInstalledQuery("mostReportedDrugsForCompany_v2", params={"companyName": companyName, "k": k, "role": role})   except:      return {"error": "Query run unsuccessful"}

Breaking this down, we’re running the “mostReportedDrugsForCompany_v2” query we installed in GraphStudio. As the optional parameters for the endpoint, we’re passing the parameters of the query. The default parameters are the ones listed in the comments of the query.

If you haven’t already, run the file. Open http://127.0.0.1:8000/mostReportedDrugsForCompany to run the query.

With that, you’ll be able to receive the results from the default parameters of query! Let’s slightly change our request to instead grab 100 drugs by passing k=100.

Passing k=100 instead

Perfect! We can now add endpoints for the rest of our queries. First, jaccard:

@app.get("/jaccard")
def read_jaccard(source: Optional[str] = "100640876", etype: Optional[str] = "hasReactions", topK: Optional[int] = 100, sampSize: Optional[int] = 100):
try:
return conn.runInstalledQuery("jaccard_nbor_reaction", params={"source": source, "etype": etype, "topK": topK, "sampSize": sampSize})
except:
return {"error": "Query run unsuccessful"}

Next, topSideEffectsForTopDrugs:

@app.get("/topSideEffectsForTopDrugs")def read_effects(companyName: Optional[str] = "PFIZER", k: Optional[int] = 5, role: Optional[str] = "PS"):   try:      return conn.runInstalledQuery("topSideEffectsForTopDrugs", params={"companyName": companyName, "k": k, "role": role})   except:      return {"error": "Query run unsuccessful"}

Fantastic! Finally, we can run them and pass different parameters as needed.

Running /topSideEffectsForTopDrugs
Running /topSideEffectsForTopDrugs with k=100 and companyName=GUERBET

Bonus: To make the JSON output easier to read, you can install this Chrome extension!

JSON output easier to read with JSON Formatter Chrome Extension

Congrats, Next Steps, and Resources!

Congrats! You have now created middleware for your UI to easily interact with your graph solution. Next, you’ll need to create your UI to call the endpoints of the API you just created. If you have any questions, feel free to post them in either the Community Forum or the Discord.

Additionally, check out these resources for more information on TigerGraph and FastAPI:

--

--