I’m having hard time figuring why I’m getting back this error after making a POST:
{"code":"cant_update_item","message":"Cannot update item","data":{"status":500}}
the data that I’m posting is this one:
post = { 'allega_file' : { '_file' : [232] } }
where ‘allega_file’ is an ACF that contains a repeater field ‘_file’ where the id of the file is attached.
I thought was an Authorization error but, after producing one of those I saw that the feedback it’s completely different.
I took the reference on how structuring the repeater JSON from this POST
https://wordpress.org/support/topic/cant-update-acfs-using-json/
Do you guys know where I’m doing it wrong?
Here you can find the python script I'm using to test the ACF to REST API
based on this example https://discussion.dreamhost.com/t/how-to-post-content-to-wordpress-using-python-and-rest-api/65166 (that works great for Posting articles, and media).
import requests
import json
user = 'user'
pythonapp = 'mykey'
url = 'http://www.example.coop/wp-json/acf/v2/page/149'
headers = {'Authorization': 'Basic ' + 'base64user:pythonapp'}
post = { 'allega_file' : { '_file' : [232] } }
r = requests.post(url + '/posts', headers=headers, json=post)
print(headers) #just to check
print(url) #just to check
print(str(r.content))
To authenticate the script into WP I'm using this plugin
https://it.wordpress.org/plugins/application-passwords/
The ACF to REST API plugin instead is this one:
https://github.com/airesvsg/acf-to-rest-api
Related
I want to list/search all the issues in Jira. I have a code like :
url = 'https://company.com/rest/api/2/search'
auth = HTTPBasicAuth("username", "password") // I tries token as well
headers = {
'Accept': 'application/json'
}
query = {
'jql': 'project=PRKJECTKEY',
'startAt': 0
}
response = requests.request(
"GET",
url,
headers=headers,
auth=auth,
params=query
)
I am not sure if the password should be token or the actual password and the url should be should be starting from companyname.com. This gives me <Response [401]> but i have all the permissions with the account.
Can someone help me with the authentication is supposed to be used this way.
I can only describe my way of accessing the JIRA-API:
1. I am using an API-key for this which one can easily create online, if one has the necessary permissions
(https://developer.atlassian.com/cloud/jira/platform/basic-auth-for-rest-apis/)
2. You need to set up the Jira-object to query issues first
user = 'firstname.familyname#account.xx'
apikey = 'xxxxxxxxxxxxxxxxx'
server = 'https://companypage.atlassian.net'
options = {
'server': server
}
jira = JIRA(options, basic_auth=(user, apikey))
3. Now, you can use the Jira-object to query with
tickets = jira.search_issues('text ~ "my search text" ORDER BY updated DESC')
Now, you can look what you got back and play with the results
for ticket in tickets:
print(ticket)
For Packages, you only need to import JIRA at the top (obviously, need to install jira first):
from jira import JIRA
Well, why don't you use atlassian-python-api?
https://community.atlassian.com/t5/Jira-articles/Atlassian-Python-API-s/ba-p/2091355
It's much easier to work with Jira via their own library. I have been working with Confluence via this and it's pretty simple. Take a look it may solve your problem.
EDIT: here is documentation. https://atlassian-python-api.readthedocs.io/
I'm trying to perform an import of a cucumber test with the Xray API on Python, to be more specific I'm trying to translate this curl on Python side (it's a multipart form) :
curl -u usr:pass -F info=#$xrayResultFilePath -F result=#$pathToCucumberJson $jiraUrl/rest/raven/1.0/import/execution/cucumber/multipart
I tried in many different ways the python code I'm stucked on looks something like this:
response = requests.post(
atc_xray_url,
auth=(creds.username, creds.password),
files={"info": open("cucumber.result.json", "rb"),
"result": open("xray_result.json", "rb")},
)
response.raise_for_status()
I also tried to change the tags, to add them in a tuple like I found on the internet, solutions found here, but no result everytime I get this error:
<status><status-code>404</status-code><message>null for uri:
The curl is working, but the Python code is not. I could use the subprocess library but this shoud be a multiplatform solution so if this could be done with a thing in Python, it would be nice.
This repository that I made available some time ago provides several code snippets, including one precisely for that use case.
Your code is similar to the following one though; you may use basic auth or personal auth tokens, if you have a Jira DC version >= 8.14.
Given the result code you obtain, the problem may be on the URL that you use, which is not clear whether it's the same or not that you have on your curl. Note that you can also use v2 of the endpoint, as I show ahead.
import requests
import json
jira_base_url = "http://192.168.56.102"
jira_username = "admin"
jira_password = "admin"
personal_access_token = "OTE0ODc2NDE2NTgxOnrhigwOreFoyNIA9lXTZaOcgbNY"
...
files = {
'result': ('cucumber.json', open(r'cucumber.json', 'rb')),
'info': ('info.json', json.dumps(info_json) )
}
# importing results using HTTP basic authentication
# response = requests.post(f'{jira_base_url}/rest/raven/2.0/import/execution/cucumber/multipart', params=params, files=files, auth=(jira_username, jira_password))
# importing results using Personal Access Tokens
headers = {'Authorization': 'Bearer ' + personal_access_token}
response = requests.post(f'{jira_base_url}/rest/raven/2.0/import/execution/cucumber/multipart', files=files, headers=headers)
I have a basic API installed as my localhost server that does functions such as add camera, star camera, list cameras, snapshot of camera frame, etc.
My problem is after following the documentation I still can't seem to interact with it well and get the response I need. Here is the code I use to log in and get validation token:
import requests
import urllib.request
import json
base_url = "http://localhostip:8080/api/user/login?"
parameters = {
"username": username,
"password": password
}
auth_tok = requests.post(base_url + urllib.parse.urlencode(parameters)).json()
print(auth_tok)
I get the correct documented response with a token, so following the documentation to add camera I need 2 parameters, URL and Name, so I did:
base_url = "http://localhostip:8080/api/camera/add?"
parameters = {
"url": 'rtsp://192.168.1.23/1',
#or video file
"url" : '/home/video/sample.mov'
"name" : 'cam1'
}
r = requests.post(base_url + urllib.parse.urlencode(parameters),headers={'Authorization': auth_tok})
when I print the response:
-print (r)
-print (r.url)
-print(r.status_code)
-print(r.json())
I get this:
<Response [500]>
http://192.168.0.162:8080/service/api/camera/add?url=rtsp%3A%2F%2Frtsp%3A%2F%2F192.168.1.23&name=cam1
500
{'code': -111, 'message': None}
According to documentation the correct url should be like this:
http://192.168.0.6:8080/service/api/camera/add?url=rtsp://192.168.1.23&name=cam1
and the response should be:
Response:
{"status":"ok"}
So why and how to make the URL POST in the correct format, because I suspect this is the issue, the URL has these encoding symbols that may be messing up the request?
When I use the web browser GUI of this API I can add the camera or even a video file to play but I'm trying to do the same with Python so I can do further processing in future.
Your problem is when you encode the ' / / ' symbol, so, in order to fix that, you need to use another function from urllib, urllib.parse.unquote(), and use as parameter your encoding function urllib.parse.urlencode(parameters):
import urllib
parameters = {
"url": 'rtsp://192.168.1.23/1',
"name" : 'cam1'
}
The results are :
print(urllib.parse.urlencode(parameters))
'url=rtsp%3A%2F%2F192.168.1.23%2F1&name=cam1'
print(urllib.parse.unquote(urllib.parse.urlencode(parameters)))
'url=rtsp://192.168.1.23/1&name=cam1'
Source https://docs.python.org/3.0/library/urllib.parse.html#urllib.parse.unquote
I have some python tools that I would like to have send updates to a hipchat room. I do this elsewhere with shell scripts, so I know it works in our environment, but I can't seem to get the token pushed to the hipchat API. Gotta be something simple.
First, this authenticates properly and delivers a message:
curl -d "room_id=xxx&from=DummyFrom&message=ThisIsATest&color=green" https://api.hipchat.com/v1/rooms/message?auth_token=yyy
But when I try to use the python "requests" module, I am getting stuck.
import requests
room_id_real="xxx"
auth_token_real="yyy"
payload={"room_id":room_id_real,"from":"DummyFrom","message":"ThisIsATest","color":"green"}
headerdata={"auth_token":auth_token_real,"format":"json"}
r=requests.post("https://api.hipchat.com/v1/rooms/message", params=payload, headers=headerdata)
print r.ok, r.status_code, r.text
Here is my error information:
False 401 {"error":{"code":401,"type":"Unauthorized","message":"Auth token not found. Please see: https:\/\/www.hipchat.com\/docs\/api\/auth"}}
Basically I don't seem to be passing the authentication token in properly. How can I get this working?
In case it helps, here's a working V2 API example. I did find the V2 API to be a bit more sensitive about getting the form of the request exactly right. But, it might be more forward-looking to conform to the V2 API (though the original question seemed to pertain to V1).
#!/usr/bin/env python
import json
from urllib2 import Request, urlopen
V2TOKEN = '--V2 API token goes here--'
ROOMID = --room-id-nr-goes-here--
# API V2, send message to room:
url = 'https://api.hipchat.com/v2/room/%d/notification' % ROOMID
message = "It's a<br><em>trap!</em>"
headers = {
"content-type": "application/json",
"authorization": "Bearer %s" % V2TOKEN}
datastr = json.dumps({
'message': message,
'color': 'yellow',
'message_format': 'html',
'notify': False})
request = Request(url, headers=headers, data=datastr)
uo = urlopen(request)
rawresponse = ''.join(uo)
uo.close()
assert uo.code == 204
Another basic example using requests:
import requests, json
amessage = 'Hello World!'
room = 'https://api.hipchat.com/v2/room/18REPLACE35/notification'
headers = {'Authorization':'Bearer UGetYourOwnAuthKey', 'Content-type':'application/json'}
requests.post(url = room, data = json.dumps({'message':amessage}), headers = headers)
As Ianzz said, try including it in the URL query string. Although clunky (you probably want to hash it!), it definitely works.
The other strange quirk is the tokens that you get through Hipchat; I had no end of problems earlier this evening using my own personal token; it seemed to correspond to v2 beta of the API. If you go in through Group Admin and get a token from there, it may help.
Old question is old.
Here's an official list of libs which use the HipChat API v2 interface
https://www.hipchat.com/docs/apiv2/libraries
Our network team uses InfoBlox to store information about IP ranges (Location, Country, etc.)
There is an API available but Infoblox's documentation and examples are not very practical.
I would like to search via the API for details about an IP. To start with - I would be happy to get anything back from the server. I modified the only example I found
import requests
import json
url = "https://10.6.75.98/wapi/v1.0/"
object_type = "network"
search_string = {'network':'10.233.84.0/22'}
response = requests.get(url + object_type, verify=False,
data=json.dumps(search_string), auth=('adminname', 'adminpass'))
print "status code: ", response.status_code
print response.text
which returns an error 400
status code: 400
{ "Error": "AdmConProtoError: Invalid input: '{\"network\": \"10.233.84.0/22\"}'",
"code": "Client.Ibap.Proto",
"text": "Invalid input: '{\"network\": \"10.233.84.0/22\"}'"
}
I would appreciate any pointers from someone who managed to get this API to work with Python.
UPDATE: Following up on the solution, below is a piece of code (it works but it is not nice, streamlined, does not perfectly checks for errors, etc.) if someone one day would have a need to do the same as I did.
def ip2site(myip): # argument is an IP we want to know the localization of (in extensible_attributes)
baseurl = "https://the_infoblox_address/wapi/v1.0/"
# first we get the network this IP is in
r = requests.get(baseurl+"ipv4address?ip_address="+myip, auth=('youruser', 'yourpassword'), verify=False)
j = simplejson.loads(r.content)
# if the IP is not in any network an error message is dumped, including among others a key 'code'
if 'code' not in j:
mynetwork = j[0]['network']
# now we get the extended atributes for that network
r = requests.get(baseurl+"network?network="+mynetwork+"&_return_fields=extensible_attributes", auth=('youruser', 'youpassword'), verify=False)
j = simplejson.loads(r.content)
location = j[0]['extensible_attributes']['Location']
ipdict[myip] = location
return location
else:
return "ERROR_IP_NOT_MAPPED_TO_SITE"
By using requests.get and json.dumps, aren't you sending a GET request while adding JSON to the query string? Essentially, doing a
GET https://10.6.75.98/wapi/v1.0/network?{\"network\": \"10.233.84.0/22\"}
I've been using the WebAPI with Perl, not Python, but if that is the way your code is trying to do things, it will probably not work very well. To send JSON to the server, do a POST and add a '_method' argument with 'GET' as the value:
POST https://10.6.75.98/wapi/v1.0/network
Content: {
"_method": "GET",
"network": "10.233.84.0/22"
}
Content-Type: application/json
Or, don't send JSON to the server and send
GET https://10.6.75.98/wapi/v1.0/network?network=10.233.84.0/22
which I am guessing you will achieve by dropping the json.dumps from your code and handing search_string to requests.get directly.