API Reference Guide
The Causely API enables developers to integrate root cause analysis capabilities into their applications and workflows. This comprehensive guide provides step-by-step examples for authentication, querying defects, and automating incident response using the Causely platform.
Getting Started with Causely API
Create API Client Credentials
Before you can use the Causely API, you need to generate API client credentials (Client ID and Secret) from the Causely platform:
-
Login to Causely:
- Go to Causely Portal
- Login with your credentials
-
Navigate to Personal Tokens:
- Click on the Profile Icon in the top-right corner
- Select "Admin Portal"
- Choose "Personal Tokens"
-
Generate Token:
- Click "Generate Token"
- Provide a description and expiration date
- Click "Create"
-
Save Credentials:
- Record your Client ID and Secret Key in a safe place
- You'll use these credentials in the examples below

API Authentication
All Causely GraphQL API requests require authentication using a Bearer token. You'll need to exchange your API client credentials for an access token using our authentication endpoint.
How to Get API Access Token
To verify that your credentials are working, you can use the following curl command. Replace <YOUR_CLIENT_ID>
and <YOUR_CLIENT_SECRET>
with the credentials you generated above:
CAUSELY_CLIENT_ID=<YOUR_CLIENT_ID>
CAUSELY_CLIENT_SECRET=<YOUR_CLIENT_SECRET>
curl -X POST https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token \
-H "Content-Type: application/json" \
-d "{
\"clientId\": \"${CAUSELY_CLIENT_ID}\",
\"secret\": \"${CAUSELY_CLIENT_SECRET}\"
}"
Example Response:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik...",
"refresh_token": "25b14169-b912-4d15-8f9c-xxxxxxxx",
"expires_in": 86400,
"expires": "Sat, 31 May 2025 22:54:23 GMT"
}
You can use the access_token
for subsequent API calls. If you want to retrieve the access token and store it in an environment variable, you can use the following curl command:
CAUSELY_CLIENT_ID=<YOUR_CLIENT_ID>
CAUSELY_CLIENT_SECRET=<YOUR_CLIENT_SECRET>
export CAUSELY_ACCESS_TOKEN=$(response=$(curl -s -w "\n%{http_code}" -X POST https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token \
-H "Content-Type: application/json" \
-d "{\"clientId\": \"${CAUSELY_CLIENT_ID}\", \"secret\": \"${CAUSELY_CLIENT_SECRET}\"}"); \
http_code=$(echo "$response" | tail -n1); \
body=$(echo "$response" | sed '$d'); \
if [ "$http_code" = "200" ]; then echo "$body" | jq -r .access_token; else echo "$body" >&2; false; fi)
You can then use the ${CAUSELY_ACCESS_TOKEN}
environment variable for subsequent API calls.
Similarly you can obtain the token using your preferred programming language.
- python
- javascript
- go
# Make sure to install the requests library: pip install requests
import os, requests
def get_causely_access_token(client_id, client_secret,
url="https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token"):
res = requests.post(url, headers={"Content-Type": "application/json"},
json={"clientId": client_id, "secret": client_secret})
if res.status_code != 200:
raise requests.HTTPError(f"Token request failed ({res.status_code}): {res.text}")
token = res.json().get("access_token")
if not token:
raise ValueError("No access_token in response.")
return token
# Example usage:
if __name__ == "__main__":
cid, secret = os.getenv("CAUSELY_CLIENT_ID"), os.getenv("CAUSELY_CLIENT_SECRET")
if not cid or not secret:
raise EnvironmentError("Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET.")
try:
token = get_causely_access_token(cid, secret)
print("Access token:", token)
except Exception as e:
print(f"Error: {e}")
const https = require('https');
function getCauselyAccessToken(clientId, clientSecret,
url = 'https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token') {
return new Promise((resolve, reject) => {
const data = JSON.stringify({ clientId, secret: clientSecret });
const req = https.request(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
}, res => {
let body = '';
res.on('data', chunk => body += chunk);
res.on('end', () => {
if (res.statusCode !== 200) {
return reject(new Error(`HTTP ${res.statusCode}: ${body}`));
}
const json = JSON.parse(body);
if (!json.access_token) return reject(new Error('No access_token in response.'));
resolve(json.access_token);
});
});
req.on('error', reject);
req.write(data);
req.end();
});
}
// Example usage
const { CAUSELY_CLIENT_ID, CAUSELY_CLIENT_SECRET } = process.env;
if (!CAUSELY_CLIENT_ID || !CAUSELY_CLIENT_SECRET) {
console.error('Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET');
process.exit(1);
}
getCauselyAccessToken(CAUSELY_CLIENT_ID, CAUSELY_CLIENT_SECRET)
.then(token => console.log('Access token:', token))
.catch(err => console.error('Error:', err.message));
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func getToken(id, secret, url string) (string, error) {
data, _ := json.Marshal(map[string]string{"clientId": id, "secret": secret})
req, _ := http.NewRequest("POST", url, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
return "", fmt.Errorf("status %d: %s", res.StatusCode, body)
}
var resp map[string]interface{}
if err := json.Unmarshal(body, &resp); err != nil {
return "", err
}
token, ok := resp["access_token"].(string)
if !ok || token == "" {
return "", fmt.Errorf("no access_token in response")
}
return token, nil
}
func main() {
id, secret := os.Getenv("CAUSELY_CLIENT_ID"), os.Getenv("CAUSELY_CLIENT_SECRET")
if id == "" || secret == "" {
fmt.Fprintln(os.Stderr, "Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET")
os.Exit(1)
}
url := "https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token"
token, err := getToken(id, secret, url)
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
fmt.Println("Access token:", token)
}
Setting Up Reusable GraphQL API Clients
To maximize efficiency and code reusability when integrating with the Causely GraphQL API, we recommend setting up proper GraphQL client libraries rather than using raw HTTP requests. This approach provides better error handling, type safety, query validation, and cleaner code that can be reused across multiple API operations.
Install GraphQL Client Libraries
Install the recommended GraphQL client libraries for your programming language to enable robust API integration with automatic query validation and enhanced developer experience:
- python
- javascript
- bash
- go
pip install gql[all] requests
npm install @apollo/client graphql
# Install gq (GraphQL CLI tool)
curl -sSL https://github.com/houseabsolute/gq/releases/latest/download/gq-Linux-x86_64.tar.gz | tar xz
# Or use your package manager, e.g., brew install gq
go get github.com/machinebox/graphql
Create Reusable GraphQL Client Functions
Implement these language-specific GraphQL client functions that integrate seamlessly with the authentication methods from the previous section. These functions provide a clean, reusable interface for executing any GraphQL query against the Causely API:
- python
- javascript
- bash
- go
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
def create_graphql_client(access_token):
"""Create a GraphQL client with authentication."""
transport = RequestsHTTPTransport(
url="https://api.causely.app/query/",
headers={"Authorization": f"Bearer {access_token}"}
)
return Client(transport=transport, fetch_schema_from_transport=True)
def post_query(client, query_string, variables=None):
"""Execute a GraphQL query using the client."""
query = gql(query_string)
return client.execute(query, variable_values=variables)
# Usage example:
# client = create_graphql_client(get_causely_access_token(client_id, secret))
# result = post_query(client, query_string, variables)
const { ApolloClient, InMemoryCache, createHttpLink, gql } = require('@apollo/client');
function createGraphQLClient(accessToken) {
const httpLink = createHttpLink({
uri: 'https://api.causely.app/query/',
headers: {
Authorization: `Bearer ${accessToken}`
}
});
return new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
}
async function postQuery(client, queryString, variables = {}) {
const result = await client.query({
query: gql(queryString),
variables,
fetchPolicy: 'no-cache'
});
return result.data;
}
// Usage example:
// const client = createGraphQLClient(await getCauselyAccessToken(clientId, secret));
// const result = await postQuery(client, queryString, variables);
# Function to execute GraphQL queries using gq
post_query() {
local query_file="$1"
local variables_file="$2"
gq https://api.causely.app/query/ \
--header "Authorization: Bearer ${CAUSELY_ACCESS_TOKEN}" \
--query-file "$query_file" \
--variables-file "$variables_file"
}
# Alternative using curl with GraphQL
post_query_curl() {
local query="$1"
local variables="$2"
curl -X POST https://api.causely.app/query/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${CAUSELY_ACCESS_TOKEN}" \
-d "{\"query\": \"$query\", \"variables\": $variables}"
}
package main
import (
"context"
"github.com/machinebox/graphql"
)
func createGraphQLClient(accessToken string) *graphql.Client {
client := graphql.NewClient("https://api.causely.app/query/")
client.WithHTTPHeader("Authorization", "Bearer "+accessToken)
return client
}
func postQuery(client *graphql.Client, queryString string, variables map[string]interface{}) (interface{}, error) {
req := graphql.NewRequest(queryString)
// Add variables to the request
for key, value := range variables {
req.Var(key, value)
}
var response interface{}
err := client.Run(context.Background(), req, &response)
return response, err
}
// Usage example:
// client := createGraphQLClient(token)
// result, err := postQuery(client, queryString, variables)
Query Examples
The following examples demonstrate how to use the Causely API to query defects and root causes using the GraphQL utilities defined above.
They make use of the functions defined to get the access token and create the GraphQL client as defined in the previous sections.
Get User Scopes
This query retrieves user scopes and access permissions for the authenticated user. User scopes define which resources and data the current user can access within the Causely platform.
- python
- javascript
- bash
- go
- graphql
import os
if __name__ == "__main__":
# Get credentials from environment
cid, secret = os.getenv("CAUSELY_CLIENT_ID"), os.getenv("CAUSELY_CLIENT_SECRET")
if not cid or not secret:
raise EnvironmentError("Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET")
# Get access token and create GraphQL client
token = get_causely_access_token(cid, secret)
client = create_graphql_client(token)
# Prepare query variables
variables = {
"filter": {
"nameExpr": ""
}
}
# Execute the query
query = """
query getUserScopes($filter: UserScopeFilter, $first: Int, $after: String, $last: Int, $before: String) {
getUserScopes(
filter: $filter
first: $first
after: $after
last: $last
before: $before
) {
totalCount
edges {
node {
id
name
audience
ownerId
lastUpdate
scopes {
typeName
typeValues
__typename
}
__typename
}
cursor
__typename
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
totalCount
__typename
}
__typename
}
}
"""
result = post_query(client, query, variables)
print(result)
const { CAUSELY_CLIENT_ID, CAUSELY_CLIENT_SECRET } = process.env;
if (!CAUSELY_CLIENT_ID || !CAUSELY_CLIENT_SECRET) {
console.error("Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET");
process.exit(1);
}
(async () => {
try {
// Get access token and create GraphQL client
const token = await getCauselyAccessToken(CAUSELY_CLIENT_ID, CAUSELY_CLIENT_SECRET);
const client = createGraphQLClient(token);
// Prepare query variables
const variables = {
filter: {
nameExpr: ""
}
};
// Execute the query
const query = `
query getUserScopes($filter: UserScopeFilter, $first: Int, $after: String, $last: Int, $before: String) {
getUserScopes(
filter: $filter
first: $first
after: $after
last: $last
before: $before
) {
totalCount
edges {
node {
id
name
audience
ownerId
lastUpdate
scopes {
typeName
typeValues
__typename
}
__typename
}
cursor
__typename
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
totalCount
__typename
}
__typename
}
}
`;
const result = await postQuery(client, query, variables);
console.log(JSON.stringify(result, null, 2));
} catch (err) {
console.error("Error:", err.message);
process.exit(1);
}
})();
# Set up credentials and get token
export CAUSELY_CLIENT_ID=<YOUR_CLIENT_ID>
export CAUSELY_CLIENT_SECRET=<YOUR_CLIENT_SECRET>
export CAUSELY_ACCESS_TOKEN=$(response=$(curl -s -w "\n%{http_code}" -X POST https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token \
-H "Content-Type: application/json" \
-d "{\"clientId\": \"${CAUSELY_CLIENT_ID}\", \"secret\": \"${CAUSELY_CLIENT_SECRET}\"}"); \
http_code=$(echo "$response" | tail -n1); \
body=$(echo "$response" | sed '$d'); \
if [ "$http_code" = "200" ]; then echo "$body" | jq -r .access_token; else echo "$body" >&2; false; fi)
# Create query and variables files
cat > user_scopes_query.graphql << 'EOF'
query getUserScopes($filter: UserScopeFilter, $first: Int, $after: String, $last: Int, $before: String) {
getUserScopes(
filter: $filter
first: $first
after: $after
last: $last
before: $before
) {
totalCount
edges {
node {
id
name
audience
ownerId
lastUpdate
scopes {
typeName
typeValues
__typename
}
__typename
}
cursor
__typename
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
totalCount
__typename
}
__typename
}
}
EOF
cat > user_scopes_variables.json << EOF
{
"filter": {
"nameExpr": ""
}
}
EOF
# Execute the query using gq (if available) or curl
if command -v gq &> /dev/null; then
post_query "user_scopes_query.graphql" "user_scopes_variables.json"
else
query=$(cat user_scopes_query.graphql | tr '\n' ' ')
variables=$(cat user_scopes_variables.json)
post_query_curl "$query" "$variables"
fi
# Clean up temporary files
rm -f user_scopes_query.graphql user_scopes_variables.json
package main
import (
"fmt"
"os"
)
func main() {
// Get credentials from environment
id, secret := os.Getenv("CAUSELY_CLIENT_ID"), os.Getenv("CAUSELY_CLIENT_SECRET")
if id == "" || secret == "" {
fmt.Fprintln(os.Stderr, "Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET")
os.Exit(1)
}
// Get access token and create GraphQL client
token, err := getToken(id, secret, "https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token")
if err != nil {
fmt.Fprintln(os.Stderr, "Error getting token:", err)
os.Exit(1)
}
client := createGraphQLClient(token)
// Prepare query variables
variables := map[string]interface{}{
"filter": map[string]interface{}{
"nameExpr": "",
},
}
// Execute the query
query := `query getUserScopes($filter: UserScopeFilter, $first: Int, $after: String, $last: Int, $before: String) {
getUserScopes(
filter: $filter
first: $first
after: $after
last: $last
before: $before
) {
totalCount
edges {
node {
id
name
audience
ownerId
lastUpdate
scopes {
typeName
typeValues
__typename
}
__typename
}
cursor
__typename
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
totalCount
__typename
}
__typename
}
}`
result, err := postQuery(client, query, variables)
if err != nil {
fmt.Fprintln(os.Stderr, "Error running query:", err)
os.Exit(1)
}
fmt.Println(result)
}
query getUserScopes($filter: UserScopeFilter, $first: Int, $after: String, $last: Int, $before: String) {
getUserScopes(
filter: $filter
first: $first
after: $after
last: $last
before: $before
) {
totalCount
edges {
node {
id
name
audience
ownerId
lastUpdate
scopes {
typeName
typeValues
__typename
}
__typename
}
cursor
__typename
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
totalCount
__typename
}
__typename
}
}
Variables:
{
"filter": {
"nameExpr": ""
}
}
High-Severity Active Defects and Root Causes
This query example demonstrates how to retrieve the first 20 high-severity, active defects and root causes from the Causely platform using the GraphQL utilities defined above.
The START_TIME is set to the current time in UTC. You may need to adjust the timestamp to your needs.
Now let's use the utilities to execute this query:
- python
- javascript
- bash
- go
- graphql
import os
from datetime import datetime, timezone
if __name__ == "__main__":
# Get credentials from environment
cid, secret = os.getenv("CAUSELY_CLIENT_ID"), os.getenv("CAUSELY_CLIENT_SECRET")
if not cid or not secret:
raise EnvironmentError("Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET")
# Get access token and create GraphQL client
token = get_causely_access_token(cid, secret)
client = create_graphql_client(token)
# Prepare query variables
start_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S") + ".000+00:00"
variables = {
"defectFilter": {
"state": "ACTIVE",
"severities": ["Critical", "High"],
"startTime": start_time,
"scopesFilter": {"scopes": []},
"entityTypes": [],
"defectNames": [],
"entityName": ""
},
"groupRecurring": True,
"first": 20
}
# Execute the query
query = """
fragment LabelFragment on Label { key value __typename }
fragment BasicEntityWithLabelsFragment on Entity { id name typeName labels { ...LabelFragment __typename } __typename }
fragment DefectFragment on Defect { id name fromTime toTime remediated serviceCount entityId entityType entity { ...BasicEntityWithLabelsFragment __typename } activeCount missingCount severity __typename }
fragment DefectRelatedOccurrencesFragment on Defect { relatedOccurrrences { id name fromTime toTime entity { id name typeName __typename } severity __typename } __typename }
fragment BasicEntityFragment on Entity { id name typeName __typename }
fragment SymptomFragmentWithoutLabels on Symptom { id name active state entityId entityType fromTime toTime isPropagated entity { ...BasicEntityFragment __typename } __typename }
fragment EventFragmentWithoutLabels on Event { id name active time entity { ...BasicEntityFragment __typename } __typename }
query defectConnection($defectFilter: DefectFilter, $groupRecurring: Boolean, $first: Int, $after: String, $last: Int, $before: String) {
defectConnection(defectFilter: $defectFilter groupRecurring: $groupRecurring first: $first after: $after last: $last before: $before) {
totalCount edges { node { ...DefectFragment ...DefectRelatedOccurrencesFragment symptoms { ...SymptomFragmentWithoutLabels __typename } events { ...EventFragmentWithoutLabels __typename } __typename } cursor __typename }
pageInfo { hasNextPage hasPreviousPage startCursor endCursor totalCount __typename } __typename
}
}
"""
result = post_query(client, query, variables)
print(result)
const { CAUSELY_CLIENT_ID, CAUSELY_CLIENT_SECRET } = process.env;
if (!CAUSELY_CLIENT_ID || !CAUSELY_CLIENT_SECRET) {
console.error("Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET");
process.exit(1);
}
(async () => {
try {
// Get access token and create GraphQL client
const token = await getCauselyAccessToken(CAUSELY_CLIENT_ID, CAUSELY_CLIENT_SECRET);
const client = createGraphQLClient(token);
// Prepare query variables
const startTime = new Date().toISOString().replace(/\.\d+Z$/, '.000+00:00');
const variables = {
defectFilter: {
state: "ACTIVE",
severities: ["Critical", "High"],
startTime,
scopesFilter: { scopes: [] },
entityTypes: [],
defectNames: [],
entityName: ""
},
groupRecurring: true,
first: 20
};
// Execute the query
const query = `
fragment LabelFragment on Label { key value __typename }
fragment BasicEntityWithLabelsFragment on Entity { id name typeName labels { ...LabelFragment __typename } __typename }
fragment DefectFragment on Defect { id name fromTime toTime remediated serviceCount entityId entityType entity { ...BasicEntityWithLabelsFragment __typename } activeCount missingCount severity __typename }
fragment DefectRelatedOccurrencesFragment on Defect { relatedOccurrrences { id name fromTime toTime entity { id name typeName __typename } severity __typename } __typename }
fragment BasicEntityFragment on Entity { id name typeName __typename }
fragment SymptomFragmentWithoutLabels on Symptom { id name active state entityId entityType fromTime toTime isPropagated entity { ...BasicEntityFragment __typename } __typename }
fragment EventFragmentWithoutLabels on Event { id name active time entity { ...BasicEntityFragment __typename } __typename }
query defectConnection($defectFilter: DefectFilter, $groupRecurring: Boolean, $first: Int, $after: String, $last: Int, $before: String) {
defectConnection(defectFilter: $defectFilter groupRecurring: $groupRecurring first: $first after: $after last: $last before: $before) {
totalCount edges { node { ...DefectFragment ...DefectRelatedOccurrencesFragment symptoms { ...SymptomFragmentWithoutLabels __typename } events { ...EventFragmentWithoutLabels __typename } __typename } cursor __typename }
pageInfo { hasNextPage hasPreviousPage startCursor endCursor totalCount __typename } __typename
}
}
`;
const result = await postQuery(client, query, variables);
console.log(JSON.stringify(result, null, 2));
} catch (err) {
console.error("Error:", err.message);
process.exit(1);
}
})();
# Set up credentials and get token
export CAUSELY_CLIENT_ID=<YOUR_CLIENT_ID>
export CAUSELY_CLIENT_SECRET=<YOUR_CLIENT_SECRET>
export CAUSELY_ACCESS_TOKEN=$(response=$(curl -s -w "\n%{http_code}" -X POST https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token \
-H "Content-Type: application/json" \
-d "{\"clientId\": \"${CAUSELY_CLIENT_ID}\", \"secret\": \"${CAUSELY_CLIENT_SECRET}\"}"); \
http_code=$(echo "$response" | tail -n1); \
body=$(echo "$response" | sed '$d'); \
if [ "$http_code" = "200" ]; then echo "$body" | jq -r .access_token; else echo "$body" >&2; false; fi)
# Create query and variables files
cat > defect_query.graphql << 'EOF'
fragment LabelFragment on Label { key value __typename }
fragment BasicEntityWithLabelsFragment on Entity { id name typeName labels { ...LabelFragment __typename } __typename }
fragment DefectFragment on Defect { id name fromTime toTime remediated serviceCount entityId entityType entity { ...BasicEntityWithLabelsFragment __typename } activeCount missingCount severity __typename }
fragment DefectRelatedOccurrencesFragment on Defect { relatedOccurrrences { id name fromTime toTime entity { id name typeName __typename } severity __typename } __typename }
fragment BasicEntityFragment on Entity { id name typeName __typename }
fragment SymptomFragmentWithoutLabels on Symptom { id name active state entityId entityType fromTime toTime isPropagated entity { ...BasicEntityFragment __typename } __typename }
fragment EventFragmentWithoutLabels on Event { id name active time entity { ...BasicEntityFragment __typename } __typename }
query defectConnection($defectFilter: DefectFilter, $groupRecurring: Boolean, $first: Int, $after: String, $last: Int, $before: String) {
defectConnection(defectFilter: $defectFilter groupRecurring: $groupRecurring first: $first after: $after last: $last before: $before) {
totalCount edges { node { ...DefectFragment ...DefectRelatedOccurrencesFragment symptoms { ...SymptomFragmentWithoutLabels __typename } events { ...EventFragmentWithoutLabels __typename } __typename } cursor __typename }
pageInfo { hasNextPage hasPreviousPage startCursor endCursor totalCount __typename } __typename
}
}
EOF
START_TIME="$(TZ=UTC date +%Y-%m-%dT%H:%M:%S).000+00:00"
cat > variables.json << EOF
{
"defectFilter": {
"state": "ACTIVE",
"severities": ["Critical", "High"],
"startTime": "${START_TIME}",
"scopesFilter": {"scopes": []},
"entityTypes": [],
"defectNames": [],
"entityName": ""
},
"groupRecurring": true,
"first": 20
}
EOF
# Execute the query using gq (if available) or curl
if command -v gq &> /dev/null; then
post_query "defect_query.graphql" "variables.json"
else
query=$(cat defect_query.graphql | tr '\n' ' ')
variables=$(cat variables.json)
post_query_curl "$query" "$variables"
fi
# Clean up temporary files
rm -f defect_query.graphql variables.json
package main
import (
"fmt"
"os"
"time"
)
func main() {
// Get credentials from environment
id, secret := os.Getenv("CAUSELY_CLIENT_ID"), os.Getenv("CAUSELY_CLIENT_SECRET")
if id == "" || secret == "" {
fmt.Fprintln(os.Stderr, "Missing CAUSELY_CLIENT_ID or CAUSELY_CLIENT_SECRET")
os.Exit(1)
}
// Get access token and create GraphQL client
token, err := getToken(id, secret, "https://auth.causely.app/frontegg/identity/resources/auth/v2/api-token")
if err != nil {
fmt.Fprintln(os.Stderr, "Error getting token:", err)
os.Exit(1)
}
client := createGraphQLClient(token)
// Prepare query variables
startTime := time.Now().UTC().Format("2006-01-02T15:04:05") + ".000+00:00"
variables := map[string]interface{}{
"defectFilter": map[string]interface{}{
"state": "ACTIVE",
"severities": []string{"Critical", "High"},
"startTime": startTime,
"scopesFilter": map[string]interface{}{"scopes": []string{}},
"entityTypes": []string{},
"defectNames": []string{},
"entityName": "",
},
"groupRecurring": true,
"first": 20,
}
// Execute the query
query := `fragment LabelFragment on Label { key value __typename } fragment BasicEntityWithLabelsFragment on Entity { id name typeName labels { ...LabelFragment __typename } __typename } fragment DefectFragment on Defect { id name fromTime toTime remediated serviceCount entityId entityType entity { ...BasicEntityWithLabelsFragment __typename } activeCount missingCount severity __typename } fragment DefectRelatedOccurrencesFragment on Defect { relatedOccurrrences { id name fromTime toTime entity { id name typeName __typename } severity __typename } __typename } fragment BasicEntityFragment on Entity { id name typeName __typename } fragment SymptomFragmentWithoutLabels on Symptom { id name active state entityId entityType fromTime toTime isPropagated entity { ...BasicEntityFragment __typename } __typename } fragment EventFragmentWithoutLabels on Event { id name active time entity { ...BasicEntityFragment __typename } __typename } query defectConnection($defectFilter: DefectFilter, $groupRecurring: Boolean, $first: Int, $after: String, $last: Int, $before: String) { defectConnection(defectFilter: $defectFilter groupRecurring: $groupRecurring first: $first after: $after last: $last before: $before) { totalCount edges { node { ...DefectFragment ...DefectRelatedOccurrencesFragment symptoms { ...SymptomFragmentWithoutLabels __typename } events { ...EventFragmentWithoutLabels __typename } __typename } cursor __typename } pageInfo { hasNextPage hasPreviousPage startCursor endCursor totalCount __typename } __typename } }`
result, err := postQuery(client, query, variables)
if err != nil {
fmt.Fprintln(os.Stderr, "Error running query:", err)
os.Exit(1)
}
fmt.Println(result)
}
First, let's define the GraphQL query and variables:
fragment LabelFragment on Label {
key
value
__typename
}
fragment BasicEntityWithLabelsFragment on Entity {
id
name
typeName
labels {
...LabelFragment
__typename
}
__typename
}
fragment DefectFragment on Defect {
id
name
fromTime
toTime
remediated
serviceCount
entityId
entityType
entity {
...BasicEntityWithLabelsFragment
__typename
}
activeCount
missingCount
severity
__typename
}
fragment DefectRelatedOccurrencesFragment on Defect {
relatedOccurrrences {
id
name
fromTime
toTime
entity {
id
name
typeName
__typename
}
severity
__typename
}
__typename
}
fragment BasicEntityFragment on Entity {
id
name
typeName
__typename
}
fragment SymptomFragmentWithoutLabels on Symptom {
id
name
active
state
entityId
entityType
fromTime
toTime
isPropagated
entity {
...BasicEntityFragment
__typename
}
__typename
}
fragment EventFragmentWithoutLabels on Event {
id
name
active
time
entity {
...BasicEntityFragment
__typename
}
__typename
}
query defectConnection($defectFilter: DefectFilter, $groupRecurring: Boolean, $first: Int, $after: String, $last: Int, $before: String) {
defectConnection(
defectFilter: $defectFilter
groupRecurring: $groupRecurring
first: $first
after: $after
last: $last
before: $before
) {
totalCount
edges {
node {
...DefectFragment
...DefectRelatedOccurrencesFragment
symptoms {
...SymptomFragmentWithoutLabels
__typename
}
events {
...EventFragmentWithoutLabels
__typename
}
__typename
}
cursor
__typename
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
totalCount
__typename
}
__typename
}
}
API Support
For technical questions about the Causely GraphQL API, contact our support team for assistance with integration challenges.