This example demonstrates how to use external web services with Cytoscape. As an example, we will use KEGG REST API.
In addition to basic cyREST setup, you need to install the following Cytoscpae App to run this workflow:
In [1]:
import requests
import json
import pandas as pd
import io
from IPython.display import Image
# Basic Setup
PORT_NUMBER = 1234
BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'
# KEGG API URL
KEGG_API_URL = 'http://rest.kegg.jp/'
# Header for posting data to the server as JSON
HEADERS = {'Content-Type': 'application/json'}
# Delete all networks in current session
requests.delete(BASE + 'session')
Out[1]:
In [2]:
# Find information about cancer from KEGG disease database.
query = 'cancer'
res = requests.get(KEGG_API_URL + '/find/disease/' + query)
pathway_list = res.content.decode('utf8')
disease_df = pd.read_csv(io.StringIO(pathway_list), delimiter='\t', header=None, names=['id', 'name'])
disease_df
Out[2]:
In [3]:
disease_ids = disease_df['id']
disease_urls = disease_ids.apply(lambda x: KEGG_API_URL + 'get/' + x)
def disease_parser(entry):
lines = entry.split('\n')
data = {}
last_key = None
for line in lines:
if '///' in line:
return data
parts = line.split(' ')
if parts[0] is not None and len(parts[0]) != 0:
last_key = parts[0]
data[parts[0]] = line.replace(parts[0], '').strip()
else:
last_val = data[last_key]
data[last_key] = last_val + '|' + line.strip()
return data
result = []
for url in disease_urls:
res = requests.get(url)
rows = disease_parser(res.content.decode('utf8'))
result.append(rows)
In [4]:
disease_df = pd.DataFrame(result)
pathways = disease_df['PATHWAY'].dropna().unique()
p_urls = []
for pathway in pathways:
entries = pathway.split('|')
for en in entries:
url = KEGG_API_URL + 'get/' + en.split(' ')[0].split('(')[0] + '/kgml'
p_urls.append(url)
In [5]:
def create_from_list(network_list):
server_res = requests.post(BASE + 'networks?source=url&collection=' + query, data=json.dumps(network_list), headers=HEADERS)
return server_res.json()
url_list = list(set(p_urls))
pathway_suids = create_from_list(url_list)
In [6]:
from py2cytoscape import cytoscapejs as cyjs
res1 = requests.get(BASE + 'styles/KEGG Style.json')
kegg_style = res1.json()
# Load local network files
kegg_url = BASE + 'networks/' + str(pathway_suids[5]['networkSUID'][0])
net1 = requests.get(kegg_url + '/views/first')
# Render it!
cyjs.render(net1.json(), style=kegg_style[0]['style'], background='white')