Skip to main content

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:

  1. Login to Causely:

  2. Navigate to Personal Tokens:

    • Click on the Profile Icon in the top-right corner
    • Select "Admin Portal"
    • Choose "Personal Tokens"
  3. Generate Token:

    • Click "Generate Token"
    • Provide a description and expiration date
    • Click "Create"
  4. Save Credentials:

    • Record your Client ID and Secret Key in a safe place
    • You'll use these credentials in the examples below
API Key Generated

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.

# 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}")

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:

pip install gql[all] requests

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:

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)

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.

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)

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.

note

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:

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)

API Support

For technical questions about the Causely GraphQL API, contact our support team for assistance with integration challenges.