I'm working with the requests library, Python 3.6, and an SMS platform's Swagger API.
I'm a little bit confused as to how I would extract a specific key:value from this JSON hierarchy.
Here is the URL to the API documentation:
api docs
I am trying to query the endpoint for a specific phone number based on an ID.
This is the URL to query: https://api.kenect.com/v1/conversations/****ID***
Here is the JSON hierarchy, so I would like to use the 'phoneNumbers' key and the 'number' value:
{
"archiveDate": 1514801105185,
"assignedTeamId": 0,
"assignedTeamName": "string",
"assignedUser": {
"departmentId": 1234,
"firstName": "John",
"id": 1234,
"inactiveDate": 1514801105185,
"includeSignature": true,
"lastName": "Doe",
"messageSignature": "Best, John Doe",
"username": "jdoe#mymail.com"
},
"contact": {
"createdDate": 1514801105185,
"emailAddress": "contact#email.com",
"externalId": "8adf-7865",
"firstActiveDate": 1514801105185,
"firstName": "Jane",
"groups": [
{
"createdDate": 1514801105185,
"id": 1234,
"locationId": 1234,
"name": "the inner circle",
"updatedDate": 1514801105185
}
],
"id": 1234,
"inactiveDate": 1514801105185,
"lastContacted": 1514801105185,
"lastName": "Doe",
"locationId": 12345,
"note": "string",
"phoneNumbers": [
{
"city": "Pleasant Grove",
"country": "US",
"createdDate": 1514801105185,
"id": 1234,
"messageOptInDate": 1514801105185,
"messageStopDate": 1514801105185,
"number": "+18015552671",
"primary": true,
"sentOptInMessageDate": 1514801105185,
"smsCapable": true,
"state": "UT",
"status": true,
"type": "CELL",
"updatedDate": 1514801105185,
"zipCode": 84062
}
],
"reviewRequestSent": 1514801105185,
"source": "LIGHTSPEED",
"updatedDate": 1514801105185
},
"createdDate": 1514801105185,
"dataAssigned": 0,
"id": 1234,
"lastMessageType": "FACEBOOK",
"lastSent": 1514801105185,
"locationId": 0,
"messages": [
{
"assignedUserId": 0,
"attachments": [
{
"contentType": "string",
"createdDate": 1514801105185,
"friendlyName": "string",
"id": 1234,
"md5": "string",
"size": 16384,
"thumbnailBase64": "string",
"updatedDate": 1514801105185
}
],
"body": "string",
"contactId": 0,
"conversationId": 0,
"error": "string",
"id": 1234,
"kind": "string",
"locationId": 0,
"outgoing": true,
"readDate": 0,
"respondedDate": 0,
"reviewRequest": true,
"sentDate": 0,
"status": "string",
"type": "FACEBOOK"
}
],
"newConversation": true,
"read": true,
"responded": true,
"snippet": "string",
"subject": "string",
"updatedDate": 1514801105185
}
And finally, here is the code I am trying. I had used a similar function to obtain the message body from this same endpoint, but it's not working for the phone number.
url='https://api.kenect.com/v1/conversations/'
h = {'accept': recContentType,
'content-type': recContentType,
'x-api-token': apiToken,
'x-api-Key': apiKey}
p={'id': id}
response=requests.get(url + id, headers=h, params=p).json()
for item in response['phoneNumber']:
pnum = item['number']
print(pnum)
What am I doing incorrectly here?
Here's the path you'll need to access to get to number:
.contact.phoneNumbers[0].number
So, you'll need this:
number = response['contact']['phoneNumbers'][0]['number']
print(number)
Or editing your code:
url='https://api.kenect.com/v1/conversations/'
h = {'accept': recContentType,
'content-type': recContentType,
'x-api-token': apiToken,
'x-api-Key': apiKey}
p={'id': id}
response=requests.get(url + id, headers=h, params=p).json()
for item in response['contact']['phoneNumbers']:
pnum = item['number']
print(pnum)
As per the comments below, the code above can result in errors if a field in the json is missing. For instance, if a reponse doesn't have a contact there will be an issue.
Consider adding some more bullet proofing to the code above as follows:
url='https://api.kenect.com/v1/conversations/'
h = {'accept': recContentType,
'content-type': recContentType,
'x-api-token': apiToken,
'x-api-Key': apiKey}
p={'id': id}
response=requests.get(url + id, headers=h, params=p).json()
if response:
if 'contact' in response:
if 'phoneNumbers' in response['contact']:
for item in response['contact']['phoneNumbers']:
pnum = item['number']
print(pnum)
I think there is enough checking in the new version of code to avoid the error you described in the comments below. Now, we only process the response when it is non empty and when it contains a contact key which in turn has to contain the phoneNumbers key. There is still an opportunity to print None, when a phoneNumber doesn't contain a number, but that won't generate an error. Just be aware that pnum could be None.
Related
I am creating posts on my site with the Wordpress API, using Python.
Everything works well.
When I am trying to update a post, it doesn't update.
I have no idea if the problem is in my code, or maybe a setting I should change?
In this example I am trying to change a simple setting on a post with just a title. Nothing fancy.
import requests
import json
import base64
credentials = "username:password"
token = base64.b64encode(credentials.encode())
post_url = "https://www.example.com/wp-json/wp/v2/posts"
header = {"Authorization": "Basic " + token.decode('utf-8'), "Content-Type":"application/json"}
postID = "1122"
data_to_send = {"comment_status": "closed"}
json_to_send = json.dumps(data_to_send)
response = requests.post(post_url + "/" + postID , headers=header, json=json_to_send)
Here is the response. The "modified" time is correct (and is also reflected in the site admin) but the value of comment_status has not changed.
Any help with this will be greatly appreciated.
{
"id": 1122,
"date": "2022-02-03T21:24:32",
"date_gmt": "2022-02-03T19:24:32",
"guid": {
"rendered": "https:\\/\\/www.example.com\\/?p=1122"
},
"modified": "2022-02-03T21:24:32",
"modified_gmt": "2022-02-03T19:24:32",
"slug": "",
"status": "draft",
"type": "post",
"link": "https:\\/\\/www.example.com\\/?p=1122",
"title": {
"rendered": "title"
},
"content": {
"rendered": "",
"protected": false
},
"excerpt": {
"rendered": "",
"protected": false
},
"author": 1,
"featured_media": 0,
"comment_status": "open",
"ping_status": "open",
"sticky": false,
"template": "",
"format": "standard",
"meta": [],
"categories": [1],
"tags": [],
"acf": {
"Description": "",
"first_page_image_id": "",
"Date": "",
"Authors": "",
"Publisher": "",
"Filename": "",
"Format": "",
"Donated_by": "",
"ocr": "",
"Series": ""
},
"_links": {
"self": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts\\/1122"
}
],
"collection": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts"
}
],
"about": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/types\\/post"
}
],
"author": [{
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/users\\/1"
}
],
"replies": [{
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/comments?post=1122"
}
],
"version-history": [{
"count": 1,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts\\/1122\\/revisions"
}
],
"predecessor-version": [{
"id": 1123,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts\\/1122\\/revisions\\/1123"
}
],
"wp:attachment": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/media?parent=1122"
}
],
"wp:term": [{
"taxonomy": "category",
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/categories?post=1122"
}, {
"taxonomy": "post_tag",
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/tags?post=1122"
}
],
"curies": [{
"name": "wp",
"href": "https:\\/\\/api.w.org\\/{rel}",
"templated": true
}
]
}
}
I am using MSGraph Api with Python as a backend and angular as a frontend to pull data but given output is showing in json format with all metadata i want to show specific data from it. How can i do that.
Python Code:
#app.route('/getChannel',methods=['GET','POST'])
def Channels():
token = _get_token_from_cache(app_config.SCOPE)
if not token:
return redirect(url_for("login"))
channel_data = requests.get(
app_config.ChannelURL,
headers={'Authorization': 'Bearer ' + token['access_token']},
).json()['value']
return render_template('team.html',result=channel_data)
json output
[
{
"createdDateTime": "2021-05-08T04:47:39.67Z",
"description": null,
"displayName": "General",
"email": "",
"id": "19:c9f316c845794a21a1ff2ba50be2bb1e#thread.tacv2",
"isFavoriteByDefault": null,
"membershipType": "standard",
"webUrl":
},
{
"createdDateTime": "2021-05-08T05:00:11.348Z",
"description": null,
"displayName": "Developement",
"email": "",
"id": "19:da1aff92f51f416c9390881e2fa70716#thread.tacv2",
"isFavoriteByDefault": true,
"membershipType": "standard",
"webUrl":
},
{
"createdDateTime": "2021-05-09T15:16:46.27Z",
"description": "testing",
"displayName": "channel1",
"email": "",
"id": "19:e81758e4858e4f598d31214282d6c100#thread.tacv2",
"isFavoriteByDefault": false,
"membershipType": "standard",
"webUrl":
}
]
i have a sample json file from a webhook response and i will want to extract just two data set from the JSON how can i do that using python. assuming i want to get the subscription code, and plan code values. thanks in anticipation
"event": "subscription.create",
"data": {
"domain": "test",
"status": "active",
"subscription_code": "SUB_vsyqdmlzble3uii",
"amount": 50000,
"cron_expression": "0 0 28 * *",
"next_payment_date": "2016-05-19T07:00:00.000Z",
"open_invoice": null,
"createdAt": "2016-03-20T00:23:24.000Z",
"plan": {
"name": "Monthly retainer",
"plan_code": "PLN_gx2wn530m0i3w3m",
"description": null,
"amount": 50000,
"interval": "monthly",
"send_invoices": true,
"send_sms": true,
"currency": "NGN"
},
"authorization": {
"authorization_code": "AUTH_96xphygz",
"bin": "539983",
"last4": "7357",
"exp_month": "10",
"exp_year": "2017",
"card_type": "MASTERCARD DEBIT",
"bank": "GTBANK",
"country_code": "NG",
"brand": "MASTERCARD"
},
"customer": {
"first_name": "BoJack",
"last_name": "Horseman",
"email": "bojack#horsinaround.com",
"customer_code": "CUS_xnxdt6s1zg1f4nx",
"phone": "",
"metadata": {},
"risk_action": "default"
},
"created_at": "2016-10-01T10:59:59.000Z"
}
}
You can use the built-in json library. For example:
import json
#if your json is in file
dict_from_file = json.load(open("foo.json"))
#if your json is in a string
dict_from_string = json.loads(string)
I have a little problem with making paypal invoices using paypal sdk in my django project. when I trying to execute this code
invoice_id = ''
invoice = Invoice({
"merchant_info": {
"email": '', # You must change this to your sandbox email account
"first_name": str(merchant.first_name),
"last_name": str(merchant.last_name),
"business_name": str(merchant_full_name),
"phone": {
"country_code": "001",
"national_number": str(merchant.phone)
},
"address": {
"line1": str(merchant_address.address),
"city": str(merchant_address.city),
"state": str(merchant_address.state),
"postal_code": str(merchant_address.zip_code),
"country_code": "US"
}
},
"billing_info": [{"email": buyer.paypal_address}],
"items": [
{
"name": "Slab",
"quantity": 1,
"unit_price": {
"currency": "USD",
"value": float(slab.price)
}
}
],
"note": "Invoice for slab",
"payment_term": {
"term_type": "NET_45"
},
"shipping_info": {
"first_name": buyer.first_name,
"last_name": buyer.last_name,
"business_name": str(buyer_full_name),
"phone": {
"country_code": "001",
"national_number": str(buyer.phone)
},
"address": {
"line1": str(buyer_address.address),
"city": str(buyer_address.city),
"state": str(buyer_address.state),
"postal_code": str(buyer_address.zip_code),
"country_code": "US"
}
},
"shipping_cost": {
"amount": {
"currency": "USD",
"value": 0
}
}
})
if invoice.create():
print(json.dumps(invoice.to_dict(), sort_keys=False, indent=4))
invoice_id = invoice['id']
return invoice_id
else:
print(invoice.error)
My server return me those errors
INFO:paypalrestsdk.api:Request[POST]:
https://api.sandbox.paypal.com/v1/oauth2/token
INFO:paypalrestsdk.api:Response[200]: OK, Duration: 1.156739s.
INFO:paypalrestsdk.api:PayPal-Request-Id:
660f7807-961f-4460-bafd-18412b489a91
INFO:paypalrestsdk.api:Request[POST]:
https://api.sandbox.paypal.com/v1/invoicing/invoices
INFO:paypalrestsdk.api:Response[401]: Unauthorized, Duration:
1.213655s. INFO:paypalrestsdk.api:Request[POST]: https://api.sandbox.paypal.com/v1/oauth2/token
INFO:paypalrestsdk.api:Response[200]: OK, Duration: 1.53491s.
As I understand it's a problem with paypal token, right?
You need to authenticate your request:
import requests, base64
# you can only encode byte objects
credentials = b"userid:password"
b64Val = base64.b64encode(credentials)
r=requests.post(api_URL,
headers={"Authorization": "Basic %s" % b64Val},
data=payload)
I'm not a developer so sorry if this is a dumb question or if my terminology is incorrect. I'm writing a script to make calls to our CMDB's API but i'm not sure how to handle the data that is being sent back from it. It appears to be a list type but I can't reference anything by key names. Is there a way to convert it to something that i can easily manipulate and pull data out of?
Here is my code:
import requests
import json
r=requests.post('API.URL', data={'grant_type': 'password', 'client_id':'#######', 'username': 'user', 'password': 'password'})
json_data = json.loads(r.content)
token = json_data['access_token']
data ={
"filters": [
{
"fieldId": "937905400191ae67dd03ab4b79968fcbaa264b1a75",
"operator": "eq",
"value": "hostname"
}
],
"fields":[
'9426b6ddf3cb971488517145e39efc5aa7f16fec46',
'9343f8800b3917f26533954918a6388ae8c863507f',
'9379053db492ece14816704ef5a9e3e567e217511b',
'9343f93fc4c8422bcf24e74a9a86035bb7d0248b00',
'941ba290776d6f51ce35664246927b958330a753b2'
],
"association": "Configuration Item",
"busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8",
"includeAllFields": 'false',
"pageNumber": 0,
"pageSize": 300,
"scope": "Global",
"scopeOwner": "(None)",
"searchName": "APItest"
}
payload = json.dumps(data)
headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization':'bearer '+token}
search=requests.post('http://API.URL', headers=headers, data=payload)
search_json = json.loads(search.content)
bo = search_json['businessObjects']
print(bo)
Here's the response:
[
{
"busObRecId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1",
"hasError": false,
"links": [
{
"url": "http://URL",
"name": "Delete Record"
}
],
"fields": [
{
"displayName": "Business Sponsor",
"name": "Business Sponsor",
"value": "",
"html": null,
"dirty": false,
"fieldId": "9426b6ddf3cb971488517145e39efc5aa7f16fec46"
},
{
"displayName": "Owned By",
"name": "Owned By",
"value": "John Doe",
"html": null,
"dirty": false,
"fieldId": "9343f8800b3917f26533954918a6388ae8c863507f"
},
{
"displayName": "Asset Status",
"name": "Asset Status",
"value": "Active",
"html": null,
"dirty": false,
"fieldId": "9379053db492ece14816704ef5a9e3e567e217511b"
},
{
"displayName": "Description",
"name": "Description",
"value": "Automation Server",
"html": null,
"dirty": false,
"fieldId": "9343f93fc4c8422bcf24e74a9a86035bb7d0248b00"
},
{
"displayName": "Data Center Location",
"name": "Data Center Location",
"value": "",
"html": null,
"dirty": false,
"fieldId": "941ba290776d6f51ce35664246927b958330a753b2"
}
],
"errorMessage": null,
"busObPublicId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1",
"busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8",
"errorCode": null
}
]
type() shows the object bo as a list and len() says it only has one element so I'm not sure how to pull data out of it without hacking away at it stripping out characters.
The reason why you cannot reference anything by key names is the fact that your output is a list. A list which is only containing one single dictionary element. If you print out
bo[0]
you get the whole data, without the [ and ] symbols. As for the dictionary now we can access different elements by keys, e.g.:
print(bo["busObId"])
will return the following value:
93dada9f640056ce1dc67b4d4bb801f69104894dc
Let's say you would want to print out the fieldId of the first element of "fields". You can do it the following way:
print(bo[0]["fields"][0]["fieldId"])
Hope this helped.