Interacting with the GraphQL API
This guide provides a comprehensive overview of how to design GraphQL queries within the Qytrees Integrated Development Environment (IDE) and how to seamlessly transition them into production using various programming languages.
Accessing and Using the GraphQL IDE
The Qytrees GraphQL IDE is a streamlined tool built on Apollo Explorer designed for creating and testing queries within your dashboard.
- Access the GraphQL IDE: Log into your Qytrees dashboard. Navigate to the Developer Portal via the left menu, and select GraphQL IDE.
- Query Execution:
- Input Your Query: Enter your query into the
Operation
window. - Add Variables: If your query requires variables, input them into the
Variables
window. - Execute the Query: Press the
Run
button to execute your query. The button will automatically adopt the name of your query as specified in the Operation window.
- Input Your Query: Enter your query into the
For detailed guidance on crafting queries, please refer to the section Predefined Output GraphQL Queries and subsequent ones.
Productionize with GraphQL
GraphQL is a versatile query language that can be utilized with any programming language or system capable of running HTTP requests, such as JavaScript, Python, Curl, C#, and many others. Numerous frameworks and libraries facilitate seamless interaction with GraphQL, providing robust and flexible solutions.
Example with Python
This section outlines the steps to use Python for querying the Qytrees GraphQL API.
Setup
- API Tokens Generation: To generate an API token, follow these steps:
- Login on the Dashboard and navigate to API Tokens in the Developer Portal section.
- Request API Token: Click
Request API Token
to generate a refresh token tailored to your profile. Copy this token.
This process uses JSON Web Tokens (JWT) technology. For more details, please refer to the API Tokens documentation.
- Python Environment Setup:
- Configure your preferred Python IDE such as PyCharm or Visual Studio.
- Install the necessary libraries such as
requests
in the environment.
pip install requests
Python Code
This code example from API Tokens page demonstrates how to connect to the Qytrees GraphQL API using Python. You can copy and integrate this code into your Python environment.
import requests
import json
from typing import Dict, Any
class ApiClient:
"""
A client for handling requests to an API with token-based authentication.
Attributes:
refresh_token (str): Token used to refresh the access token.
access_token (str): Current access token for making API requests.
api_url (str): Base URL for the API.
"""
def __init__(self, refresh_token: str) -> None:
self.refresh_token = refresh_token
self.access_token = None
self.api_url = 'https://services.qytrees.com/api/graphql/data-and-analytics/'
def get_access_token(self) -> None:
"""Refresh the access token."""
refresh_url = 'https://services.qytrees.com/api/dashboard/token/refresh'
refresh_data = {'refresh': self.refresh_token}
response = requests.post(refresh_url, json=refresh_data)
self.access_token = response.json().get('access')
def make_api_request(self, payload: json) -> Dict[str, Any]:
"""
Make an API request using the current access token.
Args:
payload (json): The GraphQL query payload.
Returns:
Dict[str, Any]: The API response.
Raises:
Exception: If the request fails after refreshing the token.
"""
if not self.access_token:
self.get_access_token()
headers = {
'Authorization': f'Bearer {self.access_token}',
'Content-Type': 'application/json'
}
response = requests.post(self.api_url, json=payload, headers=headers)
if response.status_code == 401: # Handle expired token
print("Access token expired. Refreshing token...")
self.get_access_token()
response = requests.post(self.api_url, json=payload, headers=headers)
if response.status_code == 401:
raise Exception(f"Failed to make API request after refreshing token: {response.text}")
return response.json()
Explanations:
- ApiClient: A class that handles your connection to the Qytrees GraphQL API. Initialize this with the refresh token you generated previously.
- get_access_token : A method that uses the
Refresh Token
to generate theAccess token
. The refresh token is long-lasting, whereas the access token is short-lived. This method is called automatically when needed. - make_api_request : A method that accepts the query payload in JSON format, generates the access token if necessary, and calls the API. The response is returned in JSON format.
To use the above code and connect to the API, insert your Refresh Token
generated above into the following snippet.
Below is an example with a simple query that you can run in your Python environment.
client = ApiClient('YOUR_REFRESH_TOKEN')
# Example GraphQL query to fetch supported assets from Qytrees for a specific instrument type and source
query = """
{
assetNames(instrumentType: SPOT, source: DERIBIT)
}
"""
try:
payload = {'query': query}
api_result = client.make_api_request(payload)
print(api_result)
except Exception as e:
print(f"An error occurred: {e}")
As you can see in the example above, the payload
is a JSON object created with the query as a string.
For examples of interacting with GraphQL using other frameworks, please refer to the API Tokens section of the Developer Portal.