GraphQL APIs

Swaleha Parvin
9 min readJul 16, 2024

--

This article covers examples for GraphQL APIS listed in the GraphQL official documentation.

Example 1: asnDatabaseInfo

Here’s an example of how you might construct an asnDatabaseInfo GraphQL query and the associated data structure for the IpDatabaseInfo type.

GraphQL Query Example

This query requests the IP ASN database information:

{
asnDatabaseInfo {
dbFilePath
updateStrategy
metadata
}
}

Example Response

Here is an example of what the response data might look like:

{
"data": {
"asnDatabaseInfo": {
"dbFilePath": "/var/lib/logscale/ip_database.mmdb",
"updateStrategy": "auto",
"metadata": "MaxMind GeoLite2 ASN Database, updated weekly"
}
}
}

Python Example with Documentation

Below is an example of how you might handle this data in Python, with appropriate documentation:

import requests
def get_asn_database_info(api_url, headers):
query = """
{
asnDatabaseInfo {
dbFilePath
updateStrategy
metadata
}
}
"""
try:
response = requests.post(api_url, json={'query': query}, headers=headers)
response.raise_for_status()
data = response.json()
return data.get('data', {}).get('asnDatabaseInfo', {})
except requests.exceptions.RequestException as e:
raise SystemExit(e)
def main():
"""
Main function to fetch and print ASN database information.
"""
api_url = 'https://your-logscale-instance/api/graphql'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
asn_database_info = get_asn_database_info(api_url, headers)

print("ASN Database Information:")
print(f"Database File Path: {asn_database_info.get('dbFilePath')}")
print(f"Update Strategy: {asn_database_info.get('updateStrategy')}")
print(f"Metadata: {asn_database_info.get('metadata')}")
if __name__ == '__main__':
main()

This script demonstrates how to construct a GraphQL query to retrieve the IP ASN database information and how to parse the response.

OUTPUT

ASN Database Information:
dbFilePath: /path/to/ip-database.db
updateStrategy: nightly
metadata: |
{
"version": "1.0.0",
"lastUpdated": "2024-07-10T00:00:00Z",
"source": "MaxMind"
}

Explanation

Fetches the ASN database information from the LogScale instance.
Args:
api_url (str): The endpoint URL for the GraphQL API.
headers (dict): The headers to include in the request, typically including the
Authorization token.
Returns:
dict: A dictionary containing the ASN database information.

1. GraphQL Query: The query string requests the `dbFilePath`, `updateStrategy`, and `metadata` fields from the `asnDatabaseInfo`.

2. Function `get_asn_database_info:
—Args: Takes `api_url` and `headers`.
—Request: Uses the `requests.post` method to send the GraphQL query to the API.
—Error Handling: Includes basic error handling to catch and raise HTTP request exceptions.
— Return: Returns the `asnDatabaseInfo` part of the response data.

3. Function `main`:
— API URL and Headers: Sets the API URL and headers, including the authorization token.
— Fetch Data: Calls `get_asn_database_info` to fetch the data.
— Print Data: Prints the fetched data to the console.

Usage

  1. Replace `YOUR_ACCESS_TOKEN`: Ensure you replace `’Bearer YOUR_ACCESS_TOKEN’` with your actual access token.
  2. Run the Script: Execute the script to fetch and display the ASN database information from your LogScale instance.

Example 2: blockedQueries()

Here’s an example of how you might construct a blockedQueries GraphQL query and the associated data structure for the BlockedQuery type.

GraphQL Query Example

This query requests the list of blocked query patterns:

{
blockedQueries {
id
expiresAt
expiresInMilliseconds
pattern
type
view {
id
name
}
organization {
id
name
}
}
}

Example Response

Here is an example of what the response data might look like:

{
"data": {
"blockedQueries": [
{
"id": "1",
"expiresAt": "2024-07-20T12:34:56Z",
"expiresInMilliseconds": 86400000,
"pattern": "SELECT * FROM sensitive_table",
"type": "EXACT",
"view": {
"id": "view1",
"name": "Sensitive Data View"
},
"organization": {
"id": "org1",
"name": "Example Organization"
}
},
{
"id": "2",
"expiresAt": null,
"expiresInMilliseconds": null,
"pattern": ".*DROP TABLE.*",
"type": "REGEX",
"view": null,
"organization": null
}
]
}
}

Python Example with Documentation

Below is an example of how you might handle this data in Python, with appropriate documentation:

"""
GraphQL query example for fetching blocked query patterns used by LogScale.

This script demonstrates how to construct a GraphQL query to retrieve the list of blocked query patterns
and how to parse the response.

Dependencies:
- requests
"""

import requests

def get_blocked_queries(api_url, headers):
"""
Fetches the list of blocked query patterns from the LogScale instance.

Args:
api_url (str): The endpoint URL for the GraphQL API.
headers (dict): The headers to include in the request, typically including the
Authorization token.

Returns:
list: A list of dictionaries containing the blocked query patterns.
"""
query = """
{
blockedQueries {
id
expiresAt
expiresInMilliseconds
pattern
type
view {
id
name
}
organization {
id
name
}
}
}
"""

try:
response = requests.post(api_url, json={'query': query}, headers=headers)
response.raise_for_status()
data = response.json()
return data.get('data', {}).get('blockedQueries', [])
except requests.exceptions.RequestException as e:
raise SystemExit(e)

def main():
"""
Main function to fetch and print blocked query patterns.
"""
api_url = 'https://your-logscale-instance/api/graphql'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}

blocked_queries = get_blocked_queries(api_url, headers)

print("Blocked Query Patterns:")
for query in blocked_queries:
print(f"ID: {query.get('id')}")
print(f"Expires At: {query.get('expiresAt')}")
print(f"Expires In Milliseconds: {query.get('expiresInMilliseconds')}")
print(f"Pattern: {query.get('pattern')}")
print(f"Type: {query.get('type')}")
view = query.get('view')
if view:
print(f"View ID: {view.get('id')}, View Name: {view.get('name')}")
organization = query.get('organization')
if organization:
print(f"Organization ID: {organization.get('id')}, Organization Name: {organization.get('name')}")
print()

if __name__ == '__main__':
main()

Output

Blocked Query Patterns:
ID: query1
Expires At: 2024-07-31T23:59:59Z
Expires In Milliseconds: 86400000
Pattern: SELECT * FROM sensitive_data
Type: EXACT
View ID: view1, View Name: Sensitive Data View
Organization ID: org1, Organization Name: Acme Corp

ID: query2
Expires At: 2024-07-15T23:59:59Z
Expires In Milliseconds: 43200000
Pattern: .*DROP TABLE.*
Type: REGEX
View ID: view2, View Name: Database Operations View
Organization ID: org2, Organization Name: Beta Inc

Explanation

  1. GraphQL Query: The query string requests the id, expiresAt, expiresInMilliseconds, pattern, type, view, and organization fields from the blockedQueries.
  2. Function get_blocked_queries:
  • Args: Takes api_url and headers.
  • Request: Uses the requests.post method to send the GraphQL query to the API.
  • Error Handling: Includes basic error handling to catch and raise HTTP request exceptions.
  • Return: Returns the blockedQueries part of the response data.

3. Function main:

  • API URL and Headers: Sets the API URL and headers, including the authorization token.
  • Fetch Data: Calls get_blocked_queries to fetch the data.
  • Print Data: Prints the fetched blocked query patterns to the console.

Example 3: dashboardsPage()

Here is an example of how you might construct a dashboardsPage GraphQL query and the associated data structure for the DashboardPage type.

GraphQL Query Example

This query requests a specific page of dashboards:

{
dashboardsPage(search: "example search term", pageNumber: 1, pageSize: 10) {
pageInfo {
totalPages
currentPage
pageSize
totalItems
}
page {
id
name
createdAt
updatedAt
widgets {
id
type
position
}
}
}
}

Example Response

Here is an example of what the response data might look like:

{
"data": {
"dashboardsPage": {
"pageInfo": {
"totalPages": 5,
"currentPage": 1,
"pageSize": 10,
"totalItems": 50
},
"page": [
{
"id": "dashboard1",
"name": "Sales Dashboard",
"createdAt": "2023-06-01T12:34:56Z",
"updatedAt": "2024-06-01T12:34:56Z",
"widgets": [
{
"id": "widget1",
"type": "chart",
"position": 1
},
{
"id": "widget2",
"type": "table",
"position": 2
}
]
},
{
"id": "dashboard2",
"name": "Marketing Dashboard",
"createdAt": "2023-06-02T12:34:56Z",
"updatedAt": "2024-06-02T12:34:56Z",
"widgets": [
{
"id": "widget3",
"type": "chart",
"position": 1
}
]
}
]
}
}
}

Python Example with Documentation

Below is an example of how you might handle this data in Python, with appropriate documentation:

"""
GraphQL query example for fetching a paginated list of dashboards from LogScale.

This script demonstrates how to construct a GraphQL query to retrieve a specific page of dashboards
and how to parse the response.

Dependencies:
- requests
"""

import requests

def get_dashboards_page(api_url, headers, search, page_number, page_size):
"""
Fetches a specific page of dashboards from the LogScale instance.

Args:
api_url (str): The endpoint URL for the GraphQL API.
headers (dict): The headers to include in the request, typically including the
Authorization token.
search (str): The search term to filter dashboards.
page_number (int): The page number to retrieve.
page_size (int): The number of dashboards per page.

Returns:
dict: A dictionary containing the page information and the list of dashboards.
"""
query = """
{
dashboardsPage(search: "%s", pageNumber: %d, pageSize: %d) {
pageInfo {
totalPages
currentPage
pageSize
totalItems
}
page {
id
name
createdAt
updatedAt
widgets {
id
type
position
}
}
}
}
""" % (search, page_number, page_size)

try:
response = requests.post(api_url, json={'query': query}, headers=headers)
response.raise_for_status()
data = response.json()
return data.get('data', {}).get('dashboardsPage', {})
except requests.exceptions.RequestException as e:
raise SystemExit(e)

def main():
"""
Main function to fetch and print a specific page of dashboards.
"""
api_url = 'https://your-logscale-instance/api/graphql'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
search = "example search term"
page_number = 1
page_size = 10

dashboards_page = get_dashboards_page(api_url, headers, search, page_number, page_size)

page_info = dashboards_page.get('pageInfo')
print("Page Information:")
print(f"Total Pages: {page_info.get('totalPages')}")
print(f"Current Page: {page_info.get('currentPage')}")
print(f"Page Size: {page_info.get('pageSize')}")
print(f"Total Items: {page_info.get('totalItems')}")

print("\nDashboards:")
for dashboard in dashboards_page.get('page', []):
print(f"ID: {dashboard.get('id')}")
print(f"Name: {dashboard.get('name')}")
print(f"Created At: {dashboard.get('createdAt')}")
print(f"Updated At: {dashboard.get('updatedAt')}")
print("Widgets:")
for widget in dashboard.get('widgets', []):
print(f" Widget ID: {widget.get('id')}")
print(f" Widget Type: {widget.get('type')}")
print(f" Widget Position: {widget.get('position')}")
print()

if __name__ == '__main__':
main()

Explanation

  1. GraphQL Query: The query string requests the pageInfo and page fields from the dashboardsPage, including dashboard and widget details.
  2. Function get_dashboards_page:
  • Args: Takes api_url, headers, search, page_number, and page_size.
  • Request: Uses the requests.post method to send the GraphQL query to the API.
  • Error Handling: Includes basic error handling to catch and raise HTTP request exceptions.
  • Return: Returns the dashboardsPage part of the response data.

3. Function main:

  • API URL and Headers: Sets the API URL and headers, including the authorization token.
  • Search Term, Page Number, and Page Size: Specifies the search term, page number, and page size for the query.
  • Fetch Data: Calls get_dashboards_page to fetch the data.
  • Print Data: Prints the page information and dashboard details to the console.

Output

Page Information:
Total Pages: 5
Current Page: 1
Page Size: 10
Total Items: 50

Dashboards:
ID: dashboard1
Name: Sales Dashboard
Created At: 2023-06-01T12:34:56Z
Updated At: 2024-06-01T12:34:56Z
Widgets:
Widget ID: widget1
Widget Type: chart
Widget Position: 1
Widget ID: widget2
Widget Type: table
Widget Position: 2

ID: dashboard2
Name: Marketing Dashboard
Created At: 2023-06-02T12:34:56Z
Updated At: 2024-06-02T12:34:56Z
Widgets:
Widget ID: widget3
Widget Type: chart
Widget Position: 1

Example 4: getFileContent()

Here’s an example Python script that demonstrates how to use the getFileContent GraphQL query to fetch the content of a file from a csv and print the output in YAML format.

Let’s assume we have a restaurant file named restaurant_data.csv with the following content:

Restaurant,Location,Cuisine,Rating
The Great Grill,New York,American,4.5
Sushi World,San Francisco,Japanese,4.8
Pasta Palace,Los Angeles,Italian,4.3
Taco Town,Austin,Mexican,4.6
Curry Corner,Chicago,Indian,4.7

We will create a Python script to fetch this content using the getFileContent GraphQL query and print the output in YAML format.

import requests
import yaml

def get_file_content(api_url, headers, name, file_name, offset=0, limit=100, filter_string=""):
"""
Fetches the content of a file from the LogScale instance.

Args:
api_url (str): The endpoint URL for the GraphQL API.
headers (dict): The headers to include in the request, typically including the Authorization token.
name (str): The name of the uploaded file snapshot.
file_name (str): The file name of the uploaded file snapshot.
offset (int): The offset for the query.
limit (int): The limit for the query.
filter_string (str): Any string on which to filter the data.

Returns:
dict: A dictionary containing the file content information.
"""
query = """
query getFileContent($name: String!, $fileName: String!, $offset: Int, $limit: Int, $filterString: String) {
getFileContent(name: $name, fileName: $fileName, offset: $offset, limit: $limit, filterString: $filterString) {
nameAndPath {
name
path
}
headers
lines
totalLinesCount
limit
offset
filterString
}
}
"""
variables = {
"name": name,
"fileName": file_name,
"offset": offset,
"limit": limit,
"filterString": filter_string
}

try:
response = requests.post(api_url, json={'query': query, 'variables': variables}, headers=headers)
response.raise_for_status()
data = response.json()
return data.get('data', {}).get('getFileContent', {})
except requests.exceptions.RequestException as e:
raise SystemExit(e)

def main():
"""
Main function to fetch and print file content information.
"""
api_url = 'https://your-logscale-instance/api/graphql'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
name = 'restaurant_snapshot'
file_name = 'restaurant_data.csv'

file_content_info = get_file_content(api_url, headers, name, file_name)

print("File Content Information in YAML format:")
print(yaml.dump(file_content_info, default_flow_style=False))

if __name

Output

File Content Information in YAML format:
filterString: ''
headers:
- Restaurant
- Location
- Cuisine
- Rating
limit: 100
lines:
- - The Great Grill
- New York
- American
- '4.5'
- - Sushi World
- San Francisco
- Japanese
- '4.8'
- - Pasta Palace
- Los Angeles
- Italian
- '4.3'
- - Taco Town
- Austin
- Mexican
- '4.6'
- - Curry Corner
- Chicago
- Indian
- '4.7'
nameAndPath:
name: restaurant_data.csv
path: /path/to/restaurant_data.csv
offset: 0
totalLinesCount

Explanation

  1. GraphQL Query: The query string requests specific fields from the getFileContent query.
  2. Function get_file_content:
  • Args: Takes api_url, headers, name, file_name, offset, limit, and filter_string.
  • Request: Uses the requests.post method to send the GraphQL query to the API.
  • Error Handling: Includes basic error handling to catch and raise HTTP request exceptions.
  • Return: Returns the getFileContent part of the response data.

3. Function main:

  • API URL and Headers: Sets the API URL and headers, including the authorization token.
  • Fetch Data: Calls get_file_content to fetch the data.
  • Print Data: Prints the file content information in YAML format using yaml.dump.

This script fetches the content of a restaurant file from the LogScale instance and prints it in a readable YAML format. Make sure to replace 'Bearer YOUR_ACCESS_TOKEN' with your actual access token and update the api_url, name, and file_name variables with your actual data.

--

--

Swaleha Parvin
Swaleha Parvin

Written by Swaleha Parvin

A Tech Enthusiast | I constantly learn new software concept and blog about it

No responses yet