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 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.
I am trying to parse JIRA webhook comment section properly. Now, following code works well for the first comment:
data = request.json
jira_comment = data['issue']['fields']['comment']['comments'][0].get('body')
However, every time new webhook is fired, for example, new comment is added, I can only receive the first comment in the JSON-message. If I could somehow identify each comment from another or only parse always the last comment of the issue. What would be the best way to do it or is it even possible since JIRA webhook JSON looks broken (multiple 'body' keys).
See JSON data below, to make it cleaner, use this http://jsbeautifier.org/:
{
"timestamp": 1443024903340,
"webhookEvent": "jira:issue_updated",
"user": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"issue": {
"id": "10300",
"self": "http://192.168.10.58:8080/rest/api/2/issue/10300",
"key": "DEMO-6",
"fields": {
"issuetype": {
"self": "http://192.168.10.58:8080/rest/api/2/issuetype/3",
"id": "3",
"description": "A task that needs to be done.",
"iconUrl": "http://192.168.10.58:8080/images/icons/issuetypes/task.png",
"name": "Task",
"subtask": false
},
"components": [],
"timespent": null,
"timeoriginalestimate": null,
"description": "Hey",
"project": {
"self": "http://192.168.10.58:8080/rest/api/2/project/10000",
"id": "10000",
"key": "DEMO",
"name": "DEMO",
"avatarUrls": {
"48x48": "http://192.168.10.58:8080/secure/projectavatar?avatarId=10011",
"24x24": "http://192.168.10.58:8080/secure/projectavatar?size=small&avatarId=10011",
"16x16": "http://192.168.10.58:8080/secure/projectavatar?size=xsmall&avatarId=10011",
"32x32": "http://192.168.10.58:8080/secure/projectavatar?size=medium&avatarId=10011"
}
},
"fixVersions": [],
"aggregatetimespent": null,
"resolution": null,
"timetracking": {},
"customfield_10006": null,
"attachment": [],
"customfield_10009": "0|i0000f:",
"aggregatetimeestimate": null,
"resolutiondate": null,
"workratio": -1,
"summary": "Comment test",
"lastViewed": "2015-09-23T19:14:11.979+0300",
"watches": {
"self": "http://192.168.10.58:8080/rest/api/2/issue/DEMO-6/watchers",
"watchCount": 1,
"isWatching": true
},
"creator": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"subtasks": [],
"created": "2015-09-21T17:39:14.518+0300",
"reporter": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"customfield_10000": null,
"aggregateprogress": {
"progress": 0,
"total": 0
},
"priority": {
"self": "http://192.168.10.58:8080/rest/api/2/priority/2",
"iconUrl": "http://192.168.10.58:8080/images/icons/priorities/high.png",
"name": "High",
"id": "2"
},
"customfield_10001": null,
"customfield_10100": "1234",
"customfield_10200": null,
"labels": [],
"customfield_10004": null,
"environment": null,
"timeestimate": null,
"aggregatetimeoriginalestimate": null,
"versions": [],
"duedate": null,
"progress": {
"progress": 0,
"total": 0
},
"comment": {
"startAt": 0,
"maxResults": 3,
"total": 3,
"comments": [{
"self": "http://192.168.10.58:8080/rest/api/2/issue/10300/comment/10600",
"id": "10600",
"author": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"body": "Comment 1",
"updateAuthor": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"created": "2015-09-23T19:05:26.593+0300",
"updated": "2015-09-23T19:08:07.010+0300"
}, {
"self": "http://192.168.10.58:8080/rest/api/2/issue/10300/comment/10601",
"id": "10601",
"author": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"body": "Comment 2",
"updateAuthor": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"created": "2015-09-23T19:08:13.644+0300",
"updated": "2015-09-23T19:08:13.644+0300"
}, {
"self": "http://192.168.10.58:8080/rest/api/2/issue/10300/comment/10606",
"id": "10606",
"author": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"body": "Comment 3",
"updateAuthor": {
"self": "http://192.168.10.58:8080/rest/api/2/user?username=jhdoe",
"name": "jhdoe",
"key": "jhdoe",
"emailAddress": "john.doe#corp.com",
"avatarUrls": {
"48x48": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=48",
"24x24": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=24",
"16x16": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=16",
"32x32": "http://www.gravatar.com/avatar/f94b6b6c15d155f4d4b3b2c05509ab0a?d=mm&s=32"
},
"displayName": "John Doe",
"active": true,
"timeZone": "Europe/Berlin"
},
"created": "2015-09-23T19:13:24.836+0300",
"updated": "2015-09-23T19:14:04.464+0300"
}]
},
"issuelinks": [],
"votes": {
"self": "http://192.168.10.58:8080/rest/api/2/issue/DEMO-6/votes",
"votes": 0,
"hasVoted": false
},
"worklog": {
"startAt": 0,
"maxResults": 20,
"total": 0,
"worklogs": []
},
"assignee": null,
"updated": "2015-09-23T19:15:03.338+0300",
"status": {
"self": "http://192.168.10.58:8080/rest/api/2/status/10000",
"description": "",
"iconUrl": "http://192.168.10.58:8080/images/icons/subtask.gif",
"name": "To Do",
"id": "10000",
"statusCategory": {
"self": "http://192.168.10.58:8080/rest/api/2/statuscategory/2",
"id": 2,
"key": "new",
"colorName": "blue-gray",
"name": "To Do"
}
}
}
},
"changelog": {
"id": "10611",
"items": [{
"field": "Custom ID",
"fieldtype": "custom",
"from": null,
"fromString": null,
"to": null,
"toString": "1234"
}]
}
}
Well your comment section in the json is a list of dicts so you can always get the last in the list then call .get('body')
jira_comment = data['issue']['fields']['comment']['comments'][-1].get('body')
this works because in python negative numbers in an array index are treated as going backwards in the array. so -1 gives you the last item in the array.
Does your code work when there is no comments at all?
If it doesn't consider checking that the length of the the comments array is greater than 0 or just wrap it in a try except block.
When a comment is added, the request body should contain data['comment'], which will contain the comment that triggered the issue update. You can compare data['comment']['created'] and data['comment']['updated'] to figure if the comment is new or if the comment has been edited.
see https://developer.atlassian.com/jiradev/jira-apis/webhooks