I have the following Python code that makes a POST request to Clarifai's demographics endpoint:
import requests
import pprint
headers = {
"Authorization": "Key MY_KEY",
"Content-Type": "application/json"
}
data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}
proxies = {
"http": "MY_HTTP_PROXY",
"https": "MY_HTTPS_PROXY"
}
response = requests.post('https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs', headers=headers, data=data, proxies=proxies, verify=False)
pprint.pprint(response.json())
Note that I've replaced my real api key and proxies with MY_KEY, MY_HTTP_PROXY, and MY_HTTPS_PROXY respectively.
Does anyone experienced with Clarifai know what I'm doing wrong? I saw an example of working code posted on Clarifai's own forum, but I can't see any major differences between the working code and mine.
Just convert the data passed to json.
import requests
import pprint
import json
headers = {
"Authorization": "Key MY_KEY",
"Content-Type": "application/json"
}
data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}
json_data = json.dumps(data)
proxies = {
"http": "MY_HTTP_PROXY",
"https": "MY_HTTPS_PROXY"
}
response = requests.post('https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs', headers=headers, data=json_data, proxies=proxies, verify=False)
pprint.pprint(response.json())
Needed quotes around the data variable
'data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}'
Related
I am trying to follow this example:
https://developer.atlassian.com/server/bitbucket/rest/v806/api-group-pull-requests/#api-api-latest-projects-projectkey-repos-repositoryslug-pull-requests-pullrequestid-comments-post
and I have modified my code to this:
def create_comment(pr_id, comment):
url = f"http://{baseurl}/rest/api/latest/projects/{projectKey}/repos/{repositorySlug}/pull-requests/{pr_id}/comments"
headers = {"Accept": "application/json", "Content-Type": "application/json"}
payload = json.dumps({"text": comment})
response = requests.request(
"POST",
url,
data=payload,
headers=headers,
verify=False,
auth=HTTPKerberosAuth(mutual_authentication=OPTIONAL),
)
print(response.status_code)
print(
json.dumps(
json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")
)
)
But as a response I always get:
400
{
"errors": [
{
"context": null,
"exceptionName": null,
"message": "The path query parameter is required when retrieving comments."
}
]
}
What am I doing wrong here? I am not trying to retrieve comments. I am trying to add a comment. I can add a ?path=/ to my url, but then I only get an empty list of comments.
Looks like I'm doing just about everything correct but I keep receiving this error....
Response text error:
response .text {"name":"INVALID_TRACKING_NUMBER","message":"The requested resource ID was not found","debug_id":"12345","details":[{"field":"tracker_id","value":"1234-567890","location":"path","issue":"INVALID_TRACKING_INFO"}],"links":[]}
Response status: <Response [404]>
I'm using a real transaction and a real tracking number.
I'm doing this through python and this is my code:
def paypal_oauth():
url = 'https://api-m.paypal.com/v1/oauth2/token'
headers = {
"Content-Type": "application/json",
"Accept-Language": "en_US",
}
auth = "1234-1234","0987"
data = {"grant_type":"client_credentials"}
response = requests.post(url, headers=headers, data=data, auth=(auth))
return response
def paypal_tracking(paypal_transaction_token, tracking_number, status, carrier):
try:
_paypal_oauth = paypal_oauth()
_paypal_oauth_response = _paypal_oauth.json()
except Exception as e:
print(e)
pass
access_token = _paypal_oauth_response['access_token']
url = 'https://api-m.paypal.com/v1/shipping/trackers/%s-%s/' % (paypal_transaction_token, tracking_number)
# https://api-m.paypal.com/v1/shipping/trackers/1234-567890/
carrier = carrier_code(carrier)
# This grabs carrier from a method and gets back: 'DHL'
headers = {
'Content-Type' : 'application/json',
'Authorization' : 'Bearer %s' % access_token,
}
# {'Content-Type': 'application/json', 'Authorization': 'Bearer 1234'}
data = {
"transaction_id":"%s" % paypal_transaction_token,
"tracking_number":"%s" % tracking_number,
"status": "%s" % status,
"carrier": "%s" % carrier
}
# {'transaction_id': '1234', 'tracking_number': '567890', 'status': 'SHIPPED', 'carrier': 'DHL'}
response = requests.put(url, headers=headers, data=json.dumps(data))
return HttpResponse(status=200)
Anyone with experience in paypal or using API's see my issue?
To add a tracking number (not update), use an HTTP POST request, as documented.
The URL to POST to is https://api-m.sandbox.paypal.com/v1/shipping/trackers-batch , with no additional URL parameters.
The body format is
{
"trackers": [
{
"transaction_id": "8MC585209K746392H",
"tracking_number": "443844607820",
"status": "SHIPPED",
"carrier": "FEDEX"
},
{
"transaction_id": "53Y56775AE587553X",
"tracking_number": "443844607821",
"status": "SHIPPED",
"carrier": "FEDEX"
}
]
}
Note that trackers is an array of JSON object(s).
How to send the below request using python requests library?
Request :
I have tried
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
r = session.post(url, json=json_data)
But it doesn't give the output I want.
1.Define a POST request method
import urllib3
import urllib.parse
def request_with_url(url_str, parameters=None):
"""
https://urllib3.readthedocs.io/en/latest/user-guide.html
"""
http = urllib3.PoolManager()
response = http.request("POST",
url_str,
headers={
'Content-Type' : 'application/json'
},
body=parameters)
resp_data = str(response.data, encoding="utf-8")
return resp_data
2.Call the function with your specific url and parameters
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
key = "123456"
url = "http://somewebsite.com/lib/ajax/service.php?key={0}&info=get_enrolled".format(key)
request_with_url(url, json_data)
With no more info what you want and from what url it is hard to help but.
But try adding headers with the user-agent to the post. More headers may be needed, but User-Agent is a header that is often required.
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
headers = {'User-Agent': 'Mozilla/5.0'}
r = session.post(url, json=json_data, headers=headers)
I have registered at the https://azure.microsoft.com/ru-ru/try/cognitive-services
From there I got an API-key and an endpoint https://api.cognitive.microsoft.com/inkrecognizer
Here is my code:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('POST', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
However it gives me
Response:
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
What am I doing wrong?
Here how the code should look like:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer/v1.0-preview/recognize'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('PUT', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
And you will need to add into body 'language' and 'strokes'
GIST
I am currently trying to update a Sharepoint 2013 list.
This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error:
"b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'"
Any idea of what I am doing wrong?
def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname):
login_user = ad_domain + '\\' + sharepoint_user
auth = HttpNtlmAuth(login_user, sharepoint_password)
sharepoint_url = site_url + '/_api/web/'
sharepoint_contextinfo_url = site_url + '/_api/contextinfo'
headers = {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'odata': 'verbose',
'X-RequestForceAuthentication': 'true'
}
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue']
item_id = 4991 # This id is one of the Ids returned by the code above
api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id)
update_headers = {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose",
"odata": "verbose",
"X-RequestForceAuthentication": "true",
"X-RequestDigest": form_digest_value,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False)
if r.status_code == 204:
print(str('Updated'))
else:
print(str(r.status_code))
I used your code for my scenario and fixed the problem.
I also faced the same problem. I think the way that data passed for update is not correct
Pass like below:
json_data = {
"__metadata": { "type": "SP.Data.TasksListItem" },
"Title": "updated title from Python"
}
and pass json_data to requests like below:
r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text
Note: I used SP.Data.TasksListItem as it is my type. Use http://SharePointurl/_api/web/lists/getbytitle('name')/ListItemEntityTypeFullName to find the type