Omnivoltaic ERM API Handbook: Authentication, Items Queries, and OTP Code Generation¶
URL TO ENDPOINT¶
- Below is the endpoint you will use to access Omnivoltaic API Endpoints and also access the Graphql Playground.
https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql
Login Endpoint:¶
- The login endpoint allows users to authenticate and obtain access to ERM queries and mutations that will be running on https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql.
- Use this endpoint to securely manage user authentication within your applications.
- Endpoint :
POST https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql/login
- Method: POST
- Content Type: application/json
-
Parameters:
- username (string): The username of the user.
- password (string): The user's password.
-
Use the Distributor credentials to generate an access token to use to run the queries and mutations.
mutation {
signInClient(signInCredentialsInput:{
email:""
password:""
}){
accessToken
}
}
Example Request:¶
1. In python:¶
Overview¶
This Python script demonstrates how to make a GraphQL API request to sign in a client and retrieve an access token. The script uses the requests library for making HTTP requests.
Prerequisites¶
Before using this script, ensure the following:
- Python is installed on your system.
-
The
requestslibrary is installed. You can install it using:pip install requests
Usage¶
- Open the script file in a text editor.
-
Locate the following variables and update them with your specific values:
url: The GraphQL API endpoint URL.body: The GraphQL mutation query for signing in a client.
import requests def authenticate(email, password): url = "https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql" body = """ mutation { signInUser(signInCredentials:{ email: "%s" password: "%s" }){ _id accessToken } } """ % (email, password) response = requests.post(url=url, json={"query": body}) if response.status_code == 200: data = response.json() print("this is the accesstoken", data) access_token = data.get('data', {}).get('signInUser', {}).get('accessToken') if access_token: return access_token else: print("Failed to retrieve access token") return None else: print(f"Authentication failed with status code: {response.status_code}") return None -
Save the changes to the script file.
-
Run the script using the following command:
python script.py
Output¶
The script will make a POST request to the specified GraphQL endpoint, and upon a successful response, it will output the access token received from the server.
Response:
{
"data":{
"signInClient":{
"accessToken":"${your generated access token}"
}
}
}
- Status Codes:
- 200 OK: Successful login.
- 401 Unauthorized: Invalid credentials.
- 403 Forbidden: User account disabled or other access restrictions.
Error Handling¶
If there are any errors during the request, they will be handled by the requests library, and you may modify the script to include additional error handling based on your requirements.
Dependencies¶
requests: A Python library for making HTTP requests.
2. In Node.js :¶
Overview¶
This Node.js script demonstrates how to make a GraphQL API request to sign in a client and retrieve an access token. The script uses the axios library for making HTTP requests.
Prerequisites¶
Before using this script, ensure the following:
- Node.js is installed on your system.
- The
axioslibrary is installed. You can install it using:
npm install axios
Usage¶
- Open the script file in a text editor.
- Locate the following variables and update them with your specific values:
url: The GraphQL API endpoint URL.body: The GraphQL mutation query for signing in a client.
const axios = require('axios');
const url = "https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql";
const body = `
mutation {
signInClient(signInCredentialsInput:{
email:"your@distributor.com",
password:"distributor_password"
}){
_id
accessToken
}
}
`;
axios.post(url, { query: body })
.then(response => {
const { _id, accessToken } = response.data.data.signInClient;
console.log("User ID:", _id);
console.log("Access Token:", accessToken);
})
.catch(error => {
console.error("Error:", error);
});
- Save the changes to the script file.
- Run the script using the following command:
node script.js
Output¶
The script will make a POST request to the specified GraphQL endpoint, and upon a successful response, it will output the access token received from the server.
Response:
{
data: {
signInClient: {
_id: '${your distributor id}',
accessToken: '${access-token}'
}
}
}
- Status Codes:
- 200 OK: Successful login.
- 401 Unauthorized: Invalid credentials.
- 403 Forbidden: User account disabled or other access restrictions.
Error Handling¶
If there are any errors during the request, they will be logged to the console.
Dependencies¶
axios: A promise-based HTTP client for Node.js.
Login Conclusion¶
In conclusion, this documentation provides comprehensive guides for interacting with a GraphQL Sign-in Client API using Python, Node.js, and Java. Each section outlines the necessary prerequisites, usage instructions, and relevant details for running the provided scripts or programs.
- Python Script Documentation: The Python script leverages the
requestslibrary to make a POST request to the GraphQL API endpoint. It includes guidance on updating variables, executing the script, handling errors, and dependencies. - Node.js Script Documentation: The Node.js script utilizes the
axioslibrary to achieve the same functionality. It features clear instructions on updating variables, installing dependencies, running the script, handling errors, and additional information.
Users can choose the scripting or programming language that aligns with their preferences and requirements. Additionally, the documentation encourages users to refer to the GraphQL API provider's documentation for further insights.
Code Generation Overview¶
1. Days Code - Generate Days Code¶
Endpoint: https://api.omnivoltaic.com/otp/daysCode/v2
Description¶
Days code generation involves creating a code that provides access to a specific item for a defined duration. The generated code includes information such as the decimal representation (codeDec), hexadecimal representation (codeHex), and the code type.
The process of code-generation¶
- Login using the distributor email and password as indicated above.
- Getting distributor Items to generate code for
query GetAllClientItems {
getAllClientItems(queryorder: DESC, last: 100, assetaccount: false) {
page {
edges {
cursor
node {
_id
deleteStatus
deleteAt
createdAt
updatedAt
triggers
type
actionScope
actorName
profile
idType
idString
description
creationDate
oemID
oemItemID
sellerID
sellerItemID
lifeCycle
codeGenUsed
legacyItemId
code
}
}
}
}
}
//return values
{
"data": {
"getAllClientItems": {
"page": {
"edges": [
{
"cursor": "YXJyYXljb25uZWN0aW9uOjA=",
"node": {
"_id": "677f9698818e7a7fe66a939e",
"deleteStatus": false,
"deleteAt": null,
"createdAt": "2025-01-09T09:27:52.758Z",
"updatedAt": "2025-01-09T10:08:47.050Z",
"triggers": [],
"type": "DEVICE",
"actionScope": "DEVELOPMENT",
"actorName": "eIOT",
"profile": "Off-Grid Electric Device",
"idType": "UUID",
"idString": null,
"description": "OVES Connected eIoT",
"creationDate": "2025-01-09T08:41:41.513Z",
"oemID": "OVES",
"oemItemID": "DVAV0111000999",
"sellerID": "OVES",
"sellerItemID": "DVAV0111000999",
"lifeCycle": "INITIATED",
"codeGenUsed": null,
"legacyItemId": null,
"code": null
}
},
{
"cursor": "YXJyYXljb25uZWN0aW9uOjE=",
"node": {
"_id": "677f9695818e7a7fe66a939d",
"deleteStatus": false,
"deleteAt": null,
"createdAt": "2025-01-09T09:27:50.372Z",
"updatedAt": "2025-01-09T10:08:45.421Z",
"triggers": [],
"type": "DEVICE",
"actionScope": "DEVELOPMENT",
"actorName": "eIOT",
"profile": "Off-Grid Electric Device",
"idType": "UUID",
"idString": null,
"description": "OVES Connected eIoT",
"creationDate": "2025-01-09T08:41:41.513Z",
"oemID": "OVES",
"oemItemID": "DVAV0111000998",
"sellerID": "OVES",
"sellerItemID": "DVAV0111000998",
"lifeCycle": "INITIATED",
"codeGenUsed": null,
"legacyItemId": null,
"code": null
}
},....
- Generating code for a specific distributor item either daycode or freecode
1. Python Script¶
This documentation outlines the usage of the Omnivoltaic GraphQL API for code generation. The provided Python script demonstrates how to generate a days code for a specific item using the GraphQL API. Please make sure to replace the placeholder values (payg_id, access_token) with your actual data.
- Example code
import requests
# Replace with your actual payg_id and access_token
payg_id = "62cd300d515c89ce99d82e1w"
access_token = """your_access_token_here"""
# GraphQL API Endpoint
url = "https://dev-federated-graphql-api.omnivoltaic.com/graphql"
# Request headers
headers = {"Authorization": f"Bearer {access_token}"}
# GraphQL variables
variables = {'itemId': payg_id, 'codeDays': int(4)}
# GraphQL query
query = """
mutation ($itemId: ID!, $codeDays: Int!) {
generateDaysCode(generateDaysCodeInput: {
itemId: $itemId
codeDays: $codeDays
description: "daycode"
}) {
codeType
codeHex
codeDec
}
}
"""
# Make the GraphQL request
response = requests.post(
url=url,
json={"query": query, "variables": variables},
headers=headers
)
# Handle the response
if response.status_code == 200:
data = response.json()
print(data)
else:
print("GraphQL request failed:", response.text)
Usage Instructions¶
- Replace Placeholder Values:
- Replace
payg_idwith the actual identifier of the item for which you want to generate a days code. - Replace
access_tokenwith your valid access token.
- Replace
- Run the Script:
- Execute the Python script in your preferred Python environment.
-
Review the Response:
- Check the printed output for the generated days code information, including code type, hexadecimal representation, and decimal representation.
- Example response
{'data': {'generateDaysCode': {'codeType': 'DAYSCODE', 'codeHex': 'your_generated_codeHex', 'codeDec': 'your_generated_codeDec'}}}
Important Notes¶
- Ensure your access token is valid and has the necessary permissions.
- The script demonstrates days code generation; you can adapt it for free code or reset code generation by modifying the GraphQL query accordingly.
2. Node.Js Script¶
This documentation provides details on using the Omnivoltaic GraphQL API for code generation using Node.js. The provided Node.js script demonstrates how to generate a days code for a specific item using the GraphQL API. Ensure you replace the placeholder values (payg_id, access_token) with your actual data.
- Example code
const axios = require('axios');
// Replace with your actual payg_id and access_token
const payg_id = "62cd30900875432124";
const access_token = "your_access_token_here";
// GraphQL API Endpoint
const url = "https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql";
// Request headers
const headers = {
"Authorization": `Bearer ${access_token}`
};
// GraphQL variables
const variables = {
itemId: payg_id,
codeDays: 4
};
// GraphQL query
const query = `
mutation ($itemId: ID!, $codeDays: Int!) {
generateDaysCode(generateDaysCodeInput: {
itemId: $itemId
codeDays: $codeDays
description: "daycode"
}) {
codeType
codeHex
codeDec
}
}
`;
// Make the GraphQL request
axios.post(url, { query, variables }, { headers })
.then(response => {
const data = response.data;
console.log(data);
})
.catch(error => {
console.error("GraphQL request failed:", error.message);
});
// Example of the above
mutation SignInUser {
signInUser(
signInCredentials: { email: "distributor_email", password: "your password" }
) {
accessToken
refreshToken
_id
deleteStatus
deleteAt
createdAt
updatedAt
email
agentType
agentId
hireDate
idString
type
name
profile
idType
birthDate
actionScope
roleName
subRoleName
firstName
lastName
}
generateDaysCode(
generateDaysCodeInput: {
itemId: "61a4ae46f67defrii3558sj"
codeDays: 1
description: "testing code generation"
}
) {
codeType
codeHex
codeDec
}
}
// return values
{
"data": {
"signInUser": {
"accessToken": "your_accesstoken",
"refreshToken": "your_refreshtoken",
"_id": "61811cc2bf5a3f81fbeb5d41",
"deleteStatus": false,
"deleteAt": null,
"createdAt": "2021-11-02T11:10:58.663Z",
"updatedAt": "2024-01-30T06:07:17.127Z",
"email": "ovesTestDistributor3@outlook.com",
"agentType": null,
"agentId": null,
"hireDate": null,
"idString": null,
"type": "DISTRIBUTOR",
"name": "OVES Distributor",
"profile": null,
"idType": null,
"birthDate": null,
"actionScope": null,
"roleName": "DISTRIBUTOR",
"subRoleName": null,
"firstName": null,
"lastName": null
},
"generateDaysCode": {
"codeType": "DAYSCODE",
"codeHex": "5F9378720CBB25A8",
"codeDec": "*016 035 001 460 213 591 464#"
}
}
}
Usage Instructions¶
- Replace Placeholder Values:
- Replace
payg_idwith the actual identifier of the item for which you want to generate a days code. - Replace
access_tokenwith your valid access token.
- Replace
- Run the Script:
- Execute the Node.js script using an appropriate runtime environment (Node.js).
-
Review the Response:
- Check the printed output for the generated days code information, including code type, hexadecimal representation, and decimal representation.
- Example response
{ data: { generateDaysCode: { codeType: 'DAYSCODE', 'codeHex': 'your_generated_codeHex', 'codeDec': 'your_generated_codeDec' } } }
Important Notes¶
- Ensure your access token is valid and has the necessary permissions.
- The script demonstrates days code generation; you can adapt it for free code or reset code generation by modifying the GraphQL query accordingly.
2. Free Codes¶
Endpoint: https://api.omnivoltaic.com/code/code/freecodeotp/v2
Description¶
Free code generation involves creating a code that provides access to a specific item for an undefined duration. The generated code includes information such as the decimal representation (codeDec), hexadecimal representation (codeHex), and the code type.
Python Script¶
Overview
This code snippet is a Python script that performs a GraphQL request using the requests library to a specified endpoint (https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql). The purpose of the request is to generate a free code using a GraphQL mutation named GenerateFreeCode. The code includes the necessary headers and access token for authentication.
Dependencies¶
requestslibrary: This is used to send HTTP requests to the GraphQL endpoint.
Code Structure¶
- GraphQL Mutation Variables:
payg_id: A string representing an item ID used in the GraphQL mutation.access_token: A long string representing an access token for authentication in the GraphQL request.
- GraphQL Mutation:
freevariables: A dictionary containing the variables for the GraphQL mutation.freequery: A GraphQL mutation query in the form of a string. It includes the mutation name, input variables, and the fields to be returned.
- Headers and Access Token:
headers: A dictionary containing the Authorization header with the access token for authentication.
- GraphQL Request:
requests.post(): Sends a POST request to the specified GraphQL endpoint with the GraphQL query and variables as JSON data. The response is stored in theresponsevariable.
- Response Handling:
- Checks the HTTP status code of the response. If it's 200 (OK), the script prints the generated free code. Otherwise, it prints an error message along with the response text.
Usage¶
To use this code snippet, you need to replace the payg_id and access_token with valid values. Additionally, ensure that the GraphQL endpoint and mutation details are appropriate for the specific GraphQL API you are working with.
import requests
# Replace with your actual payg_id and access_token
payg_id = "62cd300d515c89ce99d82e1w"
access_token = """your_access_token_here"""
freevariables = {'itemId': payg_id}
freequery = """
mutation GenerateFreeCode($itemId: ID!) {
generateFreeCode(generateFreeCodeInput: {
description: "free code generation"
itemId: $itemId
}) {
codeDec
codeHex
codeType
}
}
"""
# Define the headers and access token
headers = {"Authorization": f"Bearer {access_token}"}
# Make the GraphQL request
response = requests.post(
'https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql',
json={'query': freequery, 'variables': freevariables},
headers=headers
)
# Handle the response
if response.status_code == 200:
data = response.json()
print("This is free code")
print(data)
else:
print("GraphQL request failed:", response.text)
Example Output¶
- If the GraphQL request is successful (HTTP status code 200), it prints the generated free code data.
- If the request fails, it prints an error message along with the response text.
# Example Output (Success)
This is free code
{
"data": {
"generateFreeCode": {
"codeDec": "12345",
"codeHex": "0x3039",
"codeType": "FREECODE"
}
}
}
# Example Output (Failure)
GraphQL request failed: {"error": "Error message"}
Node.js Script¶
Overview¶
This Node.js script performs a GraphQL request to generate a free code using the axios library to send HTTP requests. The script includes the necessary headers and access token for authentication.
Dependencies¶
axioslibrary: Used for making HTTP requests.
Code Structure¶
- GraphQL Mutation Variables:
payg_id: A string representing an item ID used in the GraphQL mutation.access_token: A long string representing an access token for authentication in the GraphQL request.
- GraphQL Mutation:
freevariables: An object containing the variables for the GraphQL mutation.freequery: A GraphQL mutation query in the form of a string. It includes the mutation name, input variables, and the fields to be returned.
- Headers and Access Token:
headers: An object containing the Authorization header with the access token for authentication.
- GraphQL Request:
axios.post(): Sends a POST request to the specified GraphQL endpoint with the GraphQL query and variables as JSON data. The response is handled asynchronously usingasync/await.
- Response Handling:
- Checks the HTTP status code of the response. If it's 200 (OK), it prints the generated free code. Otherwise, it prints an error message along with the response data.
Usage¶
-
Install the necessary dependencies by running:
npm install axios -
Replace the
payg_idandaccess_tokenwith valid values.
const axios = require('axios');
# Replace with your actual payg_id and access_token
const payg_id = "62cd300d515c89ce99d82e1w"
const access_token = "your_access_token_here"
const freevariables = { itemId: payg_id };
const freequery = `
mutation GenerateFreeCode($itemId: ID!) {
generateFreeCode(generateFreeCodeInput: {
description: "free code generation"
itemId: $itemId
}) {
codeDec
codeHex
codeType
}
}
`;
// Define the headers and access token
const headers = { "Authorization": `Bearer ${access_token}` };
// Make the GraphQL request
axios.post('https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql', {
query: freequery,
variables: freevariables
}, {
headers: headers
})
.then(response => {
if (response.status === 200) {
const data = response.data;
console.log("This is free code");
console.log(data);
} else {
console.log("GraphQL request failed:", response.data);
}
})
.catch(error => {
console.error("Error making GraphQL request:", error.message);
});
- Ensure that the GraphQL endpoint and mutation details are appropriate for the specific GraphQL API you are working with.
Example Output:
the post method(mutation)
mutation GenerateFreeCode {
generateFreeCode(
generateFreeCodeInput: { itemId: "your_itemId", description: "test" }
) {
codeType
codeHex
codeDec
}
}
This is free code
{
"data": {
"generateFreeCode": {
"codeDec": "12345",
"codeHex": "0x3039",
"codeType": "FREECODE"
}
}
}
# Example Output (Failure)
GraphQL request failed: {"error": "Error message"}
3. Reset Codes¶
Description¶
Endpoint: https://api.omnivoltaic.com/code/code/resetcode/v2
Reset code generation involves creating a code that nullifies the generated days code, and it sets the days code to zero on the product.. The generated code includes information such as the decimal representation (codeDec), hexadecimal representation (codeHex), and the code type.
Python Script¶
Overview
This code snippet is a Python script that performs a GraphQL request using the requests library to a specified endpoint (https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql). The purpose of the request is to generate a free code using a GraphQL mutation named GenerateResetCode. The code includes the necessary headers and access token for authentication.
Dependencies¶
requestslibrary: This is used to send HTTP requests to the GraphQL endpoint.
Code Structure¶
- GraphQL Mutation Variables:
payg_id: A string representing an item ID used in the GraphQL mutation.access_token: A long string representing an access token for authentication in the GraphQL request.
- GraphQL Mutation:
freevariables: A dictionary containing the variables for the GraphQL mutation.freequery: A GraphQL mutation query in the form of a string. It includes the mutation name, input variables, and the fields to be returned.
- Headers and Access Token:
headers: A dictionary containing the Authorization header with the access token for authentication.
- GraphQL Request:
requests.post(): Sends a POST request to the specified GraphQL endpoint with the GraphQL query and variables as JSON data. The response is stored in theresponsevariable.
- Response Handling:
- Checks the HTTP status code of the response. If it's 200 (OK), the script prints the generated free code. Otherwise, it prints an error message along with the response text.
Usage¶
To use this code snippet, you need to replace the payg_id and access_token with valid values. Additionally, ensure that the GraphQL endpoint and mutation details are appropriate for the specific GraphQL API you are working with.
Example code
import requests
# Replace with your actual payg_id and access_token
payg_id = "62cd300d515c89ce99d82e1w"
access_token = """your_access_token_here"""
resetvariables = {'itemId': payg_id}
freequery = """
mutation GenerateResetCode($itemId: ID!) {
generateResetCode(generateResetCodeInput: {
description: "reset code generation"
itemId: $itemId
}) {
codeDec
codeHex
codeType
}
}
"""
# Define the headers and access token
headers = {"Authorization": f"Bearer {access_token}"}
# Make the GraphQL request
response = requests.post(
'https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql',
json={'query': freequery, 'variables': resetvariables},
headers=headers
)
# Handle the response
if response.status_code == 200:
data = response.json()
print("This is reset code")
print(data)
else:
print("GraphQL request failed:", response.text)
Example Output¶
- If the GraphQL request is successful (HTTP status code 200), it prints the generated free code data.
- If the request fails, it prints an error message along with the response text.
This is reset code
{'data': {'generateResetCode': {'codeDec': 'your generated codeDec', 'codeHex': 'your generated codeHex', 'codeType': 'RESETCODE'}}}
Node.js Script¶
Overview¶
This Node.js script performs a GraphQL request to generate a free code using the axios library to send HTTP requests. The script includes the necessary headers and access token for authentication.
Dependencies¶
axioslibrary: Used for making HTTP requests.
Code Structure¶
- GraphQL Mutation Variables:
payg_id: A string representing an item ID used in the GraphQL mutation.access_token: A long string representing an access token for authentication in the GraphQL request.
- GraphQL Mutation:
freevariables: An object containing the variables for the GraphQL mutation.freequery: A GraphQL mutation query in the form of a string. It includes the mutation name, input variables, and the fields to be returned.
- Headers and Access Token:
headers: An object containing the Authorization header with the access token for authentication.
- GraphQL Request:
axios.post(): Sends a POST request to the specified GraphQL endpoint with the GraphQL query and variables as JSON data. The response is handled asynchronously usingasync/await.
- Response Handling:
- Checks the HTTP status code of the response. If it's 200 (OK), it prints the generated free code. Otherwise, it prints an error message along with the response data.
Usage¶
-
Install the necessary dependencies by running:
npm install axios -
Replace the
payg_idandaccess_tokenwith valid values.
const axios = require('axios');
# Replace with your actual payg_id and access_token
const payg_id = "62cd300d515c89ce99d82e1w"
const access_token = "your_access_token_here"
const resetvariables = { itemId: payg_id };
const freequery = `
mutation GenerateResetCode($itemId: ID!) {
generateResetCode(generateResetCodeInput: {
description: "reset code generation"
itemId: $itemId
}) {
codeDec
codeHex
codeType
}
}
`;
// Define the headers and access token
const headers = { "Authorization": `Bearer ${access_token}` };
// Make the GraphQL request
axios.post('https://dev-federated-graphql-api.omnivoltaic.com/graphql', {
query: freequery,
variables: resetvariables
}, {
headers: headers
})
.then(response => {
if (response.status === 200) {
const data = response.data;
console.log("This is resetcd node code");
console.log(data);
} else {
console.log("GraphQL request failed:", response.data);
}
})
.catch(error => {
console.error("Error making GraphQL request:", error.message);
});
- Ensure that the GraphQL endpoint and mutation details are appropriate for the specific GraphQL API you are working with.
Example Output:
This is reset node code
{
data: {
generateResetCode: {
"codeDec": "12345",
"codeHex": "0x3039",
codeType: 'RESETCODE'
}
}
}
Fetch Code History¶
The fetch_code_history function is an asynchronous Python function that queries a GraphQL API to retrieve the code history of a specific item using its itemId. The function makes an authenticated request to the Omnivoltaic GraphQL API and returns the code history data.
Example Code¶
import httpx
import asyncio
async def fetch_code_history(item_id: str, token: str):
"""
Fetches the code history of an item from the Omnivoltaic GraphQL API.
Args:
item_id (str): The ID of the item for which the code history is requested.
token (str): The Bearer token for authentication.
Returns:
list: A list containing code history records of the specified item.
Raises:
Exception: If the request fails, returns an HTTP error, or the GraphQL response contains errors.
"""
query = f"""
query {{
getItemsForDownloadById(ids: ["{item_id}"]) {{
item {{
_id
oemID
oemItemID
}}
codeHistory {{
_id
deleteStatus
deleteAt
codeType
codeDays
codeNumber
}}
}}
}}
"""
url = "https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
}
async with httpx.AsyncClient() as client:
response = await client.post(url, json={"query": query}, headers=headers)
if response.status_code != 200:
raise Exception(f"HTTP error! Status: {response.status_code}")
result = response.json()
if "errors" in result:
raise Exception(f"GraphQL errors: {result['errors']}")
data = result.get("data", {}).get("getItemsForDownloadById", [])
if not data:
raise Exception(f"No data found for item ID: {item_id}")
return data[0].get("codeHistory", [])
# Usage Example
async def main():
item_id = "your_item_id"
token = "your_access_token"
try:
code_history = await fetch_code_history(item_id, token)
print("Code History:", code_history)
except Exception as e:
print("Error:", e)
# Run the async function
asyncio.run(main())
Function Breakdown¶
- GraphQL Query Construction
- The function dynamically inserts the
item_idinto the GraphQL query. - The query fetches item details (
_id,oemID,oemItemID) and itscodeHistory.
- The function dynamically inserts the
- API Request
- The function sends a
POSTrequest to the Omnivoltaic GraphQL API endpoint with the query. - Uses
httpx.AsyncClient()for async execution.
- The function sends a
- Response Handling
- Checks if the response status is
200. - Parses JSON response and verifies if there are errors.
- Extracts the
codeHistorylist if data exists.
- Checks if the response status is
- Error Handling
- Raises exceptions for HTTP errors, GraphQL errors, or missing data.
Expected Response¶
If the API call is successful, the function returns a list of dictionaries containing code history details:
{
getItemsForDownloadById(ids: ["67c8005b6fe08baf2c62e3bd"]) {
item {
_id
oemID
oemItemID
}
codeHistory {
_id
deleteStatus
deleteAt
codeType
codeDays
codeNumber
}
}
}
Global variables in Code Generation¶
- Frequency Limit : The time lapse between two successful code generation request should be at least 6 seconds.
- Code Limit Count : The product cannot go beyond 1096 days ; beyond 1096 the product will be unlocked.
- Daily Code Count Limit : This means that not more than 10 codes can be generated per day.
- Credit Stacking Limit : The day code count limit is set according to each specific distributor.
- Each distributor can set and reset their day code count limit according to their preference.
Error Handling¶
- If authentication fails, the script prints an error message and returns
None. - If data retrieval fails, the script prints the error message and returns
None. - Handles missing fields in the API response to avoid runtime errors.
{
"errors": [
{
"message": "Unauthorized",
"extensions": {
"code": "UNAUTHENTICATED",
"response": {
"statusCode": 401,
"message": "Unauthorized"
},
"serviceName": "10.0.101.253:3101/graphql",
"exception": {
"message": "Unauthorized",
"stacktrace": [
"GraphQLError: Unauthorized",
" at downstreamServiceError (/usr/src/app/node_modules/@apollo/gateway/dist/executeQueryPlan.js:516:16)",
" at /usr/src/app/node_modules/@apollo/gateway/dist/executeQueryPlan.js:336:59",
" at Array.map (<anonymous>)",
" at sendOperation (/usr/src/app/node_modules/@apollo/gateway/dist/executeQueryPlan.js:336:44)",
" at process.processTicksAndRejections (node:internal/process/task_queues:95:5)",
" at async /usr/src/app/node_modules/@apollo/gateway/dist/executeQueryPlan.js:251:49",
" at async executeNode (/usr/src/app/node_modules/@apollo/gateway/dist/executeQueryPlan.js:196:17)",
" at async /usr/src/app/node_modules/@apollo/gateway/dist/executeQueryPlan.js:96:35",
" at async /usr/src/app/node_modules/@apollo/gateway/dist/index.js:103:38",
" at async execute (/usr/src/app/node_modules/apollo-server-core/dist/requestPipeline.js:202:20)"
]
}
}
}
],
"data": null
}
Security Considerations¶
- Do not hardcode credentials in the script. Instead, use environment variables or a configuration file.
- Ensure HTTPS is used to encrypt credentials in transit.
- Do not expose access tokens in logs or error messages.
Important Notes¶
- Ensure your access token is valid and has the necessary permissions.
- Ensure that the GraphQL mutation and variables are correctly defined based on the schema of the GraphQL API you are working with.
- Handle sensitive information, such as access tokens, with care and consider using secure methods for storing and managing them.
- Add exception handling for network failures.
- Use
graphql-clientlibraries for better request handling.
Code Generation Conclusion¶
In both the Python and Node.js implementations provided for code generation using the Omnivoltaic GraphQL API, the fundamental logic remains consistent. The scripts demonstrate how to interact with the API, specifically focusing on generating a days code for a specified item. Here are some key takeaways: ****
- For the itemId in the mutation above it can pick any value from:
- OEMItemID
- SellerItemId
- MongoDB Id.
- These values will easen in the code generation process for all daysCodes, Free codes, and reset codes.
- Authentication:
- Both scripts utilize the provided access token for authentication. Ensure your access token is valid and has the required permissions to execute the GraphQL mutations.
- NB: The access-token expires after 24 hours.
- Variable Customization:
- The scripts allow for customization of variables such as
payg_idandcodeDays, enabling users to adapt the code generation process for different items and durations.
- The scripts allow for customization of variables such as
- Code Generation Flexibility:
- The GraphQL queries are structured to generate different types of codes (days code, free code, or reset code) by modifying the
queryvariable accordingly.
- The GraphQL queries are structured to generate different types of codes (days code, free code, or reset code) by modifying the
- Error Handling:
- Both implementations incorporate basic error handling to address potential issues during the GraphQL request. This ensures a more robust and reliable execution.
- Libraries Used:
- The Python script uses the
requestslibrary, while the Node.js script utilizesaxiosfor making HTTP requests. Users can choose the library based on their preferred environment and familiarity.
- The Python script uses the
- Documentation Emphasis:
- The accompanying documentation provides clear instructions for replacing placeholder values, running the scripts, and understanding the response output.
These scripts serve as practical starting points for developers looking to integrate code generation capabilities into their applications within the Omnivoltaic ecosystem. Whether using Python or Node.js, the flexibility provided allows for seamless customization to meet specific requirements. Additionally, users can extend these scripts to incorporate additional functionality or integrate them into larger automation workflows.
Getting Items Code get_node_id(access_token, search_term)¶
This function fetches a node ID based on a provided search term.
Parameters:¶
access_token(str): The access token retrieved from authentication.search_term(str): The search term to look up an item in the database.
Returns:¶
node_id(str): The retrieved node ID if successful, otherwiseNone.
Process:¶
- Constructs a GraphQL query to fetch items based on the search term.
- Includes the
Authorizationheader with theBearertoken. - Sends a POST request to the API endpoint with the query.
- Parses the response JSON to extract the node ID.
- Returns the node ID if found; otherwise, prints an error and returns
None.
Example Usage¶
def get_node_id(access_token, search_term):
# Updated to use getAllClientItems instead of getAllItems
query_customer = """
query {
getAllClientItems(
search: "%s"
first: 1
queryorder: DESC
assetaccount: false
) {
page {
edges {
node {
_id
oemID
oemItemID
sellerItemID
description
actorName
createdAt
updatedAt
}
}
}
}
}
""" % search_term
headers = {"Authorization": f"Bearer {access_token}"}
response = requests.post('https://production-omnivoltaic-graphql-api.omnivoltaic.com/graphql', json={'query': query_customer}, headers=headers)
if response.status_code == 200:
data = response.json()
print(data)
edges = data.get('data', {}).get('getAllClientItems', {}).get('page', {}).get('edges', [])
if edges:
node_id = edges[0]['node']['_id']
return node_id
else:
print("No edges found in response")
return None
else:
print(f"Failed to get node ID with status code: {response.status_code}")
return None
node_id = get_node_id(access_token, "06AH2502000001")
3. main()¶
This function orchestrates the authentication and data retrieval process.
Process:¶
- Calls
authenticate()with the provided credentials. - If authentication is successful, calls
get_node_id()with the retrieved access token and a predefined search term. - Prints and returns the retrieved node ID if found.
- If authentication or data retrieval fails, prints an error message.
Execution Flow:¶
- If the script is executed directly,
main()is called automatically.
Example Execution:¶
def main():
email = "user@email.com"
password = "1234567890"
customer_account_number = "06AH2502000001" # Hardcoded customer account number
access_token = authenticate(email, password)
if access_token:
node_id = get_node_id(access_token, customer_account_number)
if node_id:
print("Node ID:", node_id)
return node_id
else:
print("Failed to retrieve node ID")
return None
else:
print("Authentication failed")
return None
# This part runs the program when executed directly
if __name__ == "__main__":
main()
Example Output¶
{'data': {'signInUser': {'_id': '12345', 'accessToken': 'abcdef12345'}}}
{'data': {'getAllClientItems': {'page': {'edges': [{'node': {'_id': '67890', 'oemID': 'XYZ123', 'oemItemID': 'ABC456', 'sellerItemID': 'Seller789', 'description': 'Sample Item', 'actorName': 'User1', 'createdAt': '2025-01-01T00:00:00', 'updatedAt': '2025-01-02T00:00:00'}}]}}}}
Node ID: 67890