There are some reports created in Pendo (Like adobe ) . I want to pull this report via python api call .
I have written code which is partially incorrect .Please let me know what I'm doing wrong?
The output should be in form of table which contains 4 columns and their records.
This code is only returning - {'overall': {}, 'fields': {'pipeline': 'Required'}}
Which is strange.
pendo_key='123fgh21-ab89-ab23-21ad-bvh3r11r2sv5.ca'
import matplotlib.pyplot as pt
import pandas as pd
import numpy as np
import requests
import os
import json
import pandas as pd
from io import StringIO
pd.set_option('display.max_colwidth',0)
url= "https://app.pendo.io/api/v1/aggregation"
headers = {
'X-Pendo-Integration-Key':pendo_key,
'Content-Type':'application/json'}
payload1= json.dumps({
"response": {
"location": "request",
"mimeType": "application/json"
},
"requests": [
{
"name": "SalesEventAggregation",
"pipeline": [
{
"source": {
"salesEvents": {
"blacklist": "apply",
"salesTypeId": "dg_5w_fgtdergJ67vFdfR8kWsxi"
},
"timeSeries": {
"period": "dayRange",
"first": "now()",
"count": 1
}
}
}],
"requestId": "saleseventAggregation-rId-etr1231-561s-6d6c-7d12-351f1d21gww2"
}
]
})
response = requests.request("POST",url,headers=headers, data= payload1)
print("Status code:", response.status_code)
response_dict = json.loads(response.text)
response_dict
Status code: 422
Output:
{'overall': {}, 'fields': {'pipeline': 'Required'}}
Expected:
There are 4 columns in form of table which is not showing up and their relevant records is not showing up.
The "request" object is not an array, and the "key" should be named as "request"(singular) not as "requests"(plural).
Try
payload1= json.dumps(
{
"response": {
"location": "request",
"mimeType": "application/json"
},
"request":
{
"name": "SalesEventAggregation",
"pipeline": [
{
"source": {
"salesEvents": {
"blacklist": "apply",
"salesTypeId": "dg_5w_fgtdergJ67vFdfR8kWsxi"
},
"timeSeries": {
"period": "dayRange",
"first": "now()",
"count": 1
}
}
}],
"requestId": "saleseventAggregation-rId-etr1231-561s-6d6c-7d12-351f1d21gww2"
}
})
Related
This is a follow-up to a previous question.
Following this tutorial, I'm trying to get data from a GraphQL API and format the result into a data frame.
Here is my Python script (URL is obfuscated):
import requests
import json
import pandas as pd
url = 'https://mygraphqlserver.com/graphql/'
query = """{ resources { edges { node { id creatorPerson { firstName }} } } }"""
r = requests.post(url, json={'query': query})
json_data = json.loads(r.text)
resources_dict = json_data['data']['resources']['edges']
resources_output = pd.DataFrame(resources_dict)
print(resources_output)
Here is r.text:
{
"data": {
"resources": {
"edges": [
{
"node": {
"id": "file/pt0u8h901qni3d",
"creatorPerson": {
"firstName": "Jérémy"
}
}
},
{
"node": {
"id": "file/f218c8wn4onncj",
"creatorPerson": {
"firstName": "Jérémy"
}
}
},
{
"node": {
"id": "file/i1y7pjk7a6xy2d",
"creatorPerson": {
"firstName": "Jérémy"
}
}
}
]
}
}
}
Here is the ouput of print(resources_output) in the terminal:
node
0 {'id': 'file/pt0u8h901qni3d', 'creatorPerson':...
1 {'id': 'file/f218c8wn4onncj', 'creatorPerson':...
2 {'id': 'file/i1y7pjk7a6xy2d', 'creatorPerson':......
As you can see, I don't succeed to get a proper data frame as I expected (as shown in the tutorial).
Any idea how I can I improve my script to get a properly formatted output?
import requests import json import os
user = os.getenv("USERNAME")
key = os.getenv("KEY")
pwd = os.getenv("PASSWORD")
endpoint = f"https://pkg-graphql-api.*****.com/{user}"
headers = {"Authorization": f"Basic {key}"}
query = {
IPublications(abstract: "metabolics") {
ICitedBy(filterByYear_lte: 2020) {
isbn
count
pkgId
normalizedTitle
IPublishedInConferenceInstanceIds
}
}
}
r = requests.post(endpoint, json={"query": query}, headers=headers)
if r.status_code == 200:
print(json.dumps(r.json(), indent=2))
else:
raise Exception(f"Query failed to run with a {r.status_code}{r.text}.")
I've written this code for sending a cpt with metadata from python to WordPress, it`s one of 4 different scenarios that I have prove, practically I need to send a post with some meta field from python to WordPress using an external variable that set title and product price and product spec,
the JSON file that I need to do that asking to postman with a get request is that
[
{
"id": 3693,
"date": "2021-07-14T20:00:35",
"date_gmt": "2021-07-14T18:00:35",
"guid": {
"rendered": "http://www.mydomain.it/acme_product/spec-3/"
},
"modified": "2021-07-20T01:58:48",
"modified_gmt": "2021-07-19T23:58:48",
"slug": "spec-3",
"status": "publish",
"type": "acme_product",
"link": "http://www.mydomain.it/acme_product/spec-3/",
"title": {
"rendered": "spec"
},
"featured_media": 0,
"template": "",
"product_price": null,
"product_spec": null,
"_links": {
"self": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/acme_product/3693"
}
],
"collection": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/acme_product"
}
],
"about": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/types/acme_product"
}
],
"wp:attachment": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/media?parent=3693"
}
],
"curies": [
{
"name": "wp",
"href": "https://api.w.org/{rel}",
"templated": true
}
]
}
},
when i actually use my python code wordpress accept the post but don't fill the field for product price and product specs , some idea, what can i do with that? thanks for all
from __future__ import print_function
import base64
import sys
from datetime import datetime
import json
import requests
user= 'username'
password='auth
url = 'http://www.mydomain.it/wp-json/wp/v2/'
d= sys.argv
a_dict={}
b_dict={}
data_string = user + ':' + password
token = base64.b64encode(data_string.encode())
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
date="2021-07-14T20:00:35"
title=d[1]
slug= d[1]
status= "publish"
author="1"
##excerpt="exc post"
##format="standard"
product_price= d[2]
product_spec=d[3]
for var in ["product_price","product_spec"]:
b_dict[var]= eval(var)
print (b_dict[var])
meta= b_dict[var]
for variable in ["date", "title", "slug","status","author","product_price","product_spec"]:
a_dict[variable] = eval(variable)
r = requests.post(url + 'acme_product', headers=headers, json=a_dict)
print(r.content.decode('utf-8'))
print('Your post is published on ' + json.loads(r.content.decode('utf-8'))['link'])
I've been trying to make a discord webhook, and for some reason I can't get it to send to save my life. I have all the embeds in a json file, and am trying to run it with python. Any help would be greatly appreciated.
json file:
{
"embeds": [
{
"title": "Title",
"color": 11393254,
"fields": [
{
"name": "Name1",
"value": "value1"
},
{
"name": "Name2",
"value": "value2",
"inline": true
},
],
"footer": {
"text": "Footer",
"icon_url": "random image url"
},
"timestamp": "now",
"thumbnail": {
"url": "random image url"
}
}
],
"username": "Username"
}
python code:
import requests, json
with open('webhook.json') as json_file:
data = json.load(json_file)
url = 'https://discord.com/api/webhooks/xxxxx'
headers={"Content-Type": "application/json"}
requests.post(url, data=json.dumps(data), headers=headers)
What's the status code you get back from the POST? That could be a clue where it's going awry.
I'm currently working with some JSON data that is presenting a challenge, i need to print the device name in my script next to the latency float, i can easily print the latency float as there is a key:value , however the device name does not sit the same, therefore i cannot figure out how to print this especially as it changes for each API Url i am looping through to retrieve the data
The data i want to print is "DEVICE123-Et10"
See JSON data below,
{
"notifications": [
{
"timestamp": "511513234234",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"httpResponseTime": {
"key": "httpResponseTime",
"value": {
"float": 0
}
}
}
},
{
"timestamp": "15153324243",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"packetLoss": {
"key": "packetLoss",
"value": {
"int": 0
}
}
}
},
{
"timestamp": "151522324234",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"latency": {
"key": "latency",
"value": {
"float": 0.238756565643454
}
}
}
},
{
"timestamp": "158056745645645",
"path_elements": [
"Devices",
"DEVICE1",
"versioned-data",
"connectivityMonitor",
"status",
"hostStatus",
"DEVICE123-Et10",
"defaultStats"
],
"updates": {
"jitter": {
"key": "jitter",
"value": {
"float": 0.03500000213213
}
}
}
}
]
}
Current code i am using to loop through my URL list and get the latency:
jsonrequest = requests.get(url, cookies=cookies, verify=False).json()
try:
print(jsonrequest['notifications'][2]['updates']['latency']['value']['float'])
except KeyError:
print(jsonrequest['notifications'][1]['updates']['latency']['value']['float'])```
I went ahead and wrote a script to do what you wanted. It loops through all the notifications until a "latency" update is found. Then it takes the second-to-last item from the list, since it's always second to last.
import json
import requests
data = requests.get(url, cookies=cookies, verify=False).json()
notifications = data["notifications"]
for notification in notifications:
if notification["updates"].get("latency"):
latency = notification["updates"]["latency"]["value"]["float"]
name = notification["path_elements"][-2]
print(name, latency)
I have this json file which includes information about pages I have retrieving using this
python code:
import facebook # pip install facebook-sdk
import json
import codecs
# Create a connection to the Graph API with your access token
ACCESS_TOKEN = ''#my access token
g = facebook.GraphAPI(ACCESS_TOKEN)
s=g.request('search', { 'q' : '&','type' : 'page', 'limit' : 5000 , 'locale' : 'ar_AR' })
f = open("sampels.txt", 'w')
f.write(json.dumps(s, indent=1))
f.close()
#########################################################
this is my samples json file a snapshot of it:
{
"paging": {
"next": "https://graph.facebook.com/search?limit=5000&type=page&q=%26&locale=ar_AR&access_token=CAACEdEose0cBAIRlSOXkyk1lIMUIWViAoz5lf5t0pSdsu6lg5ZANJuYMIPZCy5N9KFQoLnpi1oxD8tNIaabWackCO31UYaAGkb38IPHxI33ldbRQDXJ02CtJrwE8NI4mZAz20OznLfuCpypDbxNYF3p9XauZCtoywoS9KJwAgW8NYgZCpD4ZBKfCBR5jjXnbcZD&offset=5000&__after_id=92240239536"
},
"data": [
{
"category": "\u0627\u0644\u062a\u0639\u0644\u064a\u0645",
"name": "The London School of Economics and Political Science - LSE",
"category_list": [
{
"id": "108051929285833",
"name": "\u0627\u0644\u0643\u0644\u064a\u0629 \u0648\u0627\u0644\u062c\u0627\u0645\u0639\u0629"
},
{
"id": "187751327923426",
"name": "\u0645\u0646\u0638\u0645\u0629 \u062a\u0639\u0644\u064a\u0645\u064a\u0629"
}
],
"id": "6127898346"
},
{
"category": "\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0628\u064a\u0639 \u0628\u0627\u0644\u062a\u062c\u0632\u0626\u0629 \u0648\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0645\u0633\u062a\u0647\u0644\u0643\u064a\u0646",
"name": "Stop & Shop",
"category_list": [
{
"id": "169207329791658",
"name": "\u0645\u062d\u0644 \u0628\u0642\u0627\u0644\u0629"
}
],
"id": "170000993071234"
},
{
"category": "\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0628\u064a\u0639 \u0628\u0627\u0644\u062a\u062c\u0632\u0626\u0629 \u0648\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0645\u0633\u062a\u0647\u0644\u0643\u064a\u0646",
"name": "C&A",
"category_list": [
{
"id": "186230924744328",
"name": "\u0645\u062a\u062c\u0631 \u0645\u0644\u0627\u0628\u0633"
}
],
"id": "109345009145382"
},
{
"category": "\u0645\u0646\u0638\u0645\u0629 \u063a\u064a\u0631 \u0631\u0628\u062d\u064a\u0629",
"name": "Rock and Roll Hall of Fame + Museum",
"category_list": [
{
"id": "396255327112122",
"name": "\u0645\u062a\u062c\u0631 \u0645\u0648\u0633\u064a\u0642\u0649"
},
now what I want to do is to get the next field in order to get my next 5000 page into my database.
I have tried a lot but I couldn't figure out away to do this can any body tell me how to take the next URL and how pass it to the request function I have in my code.?
g.request() returns a Python dict which gives you access to the paging/next url. Why do you dump it as json and write it to file instead of just using it ?