I an trying to Post CSV using python request. I am using the following code but getting this error:
{"code":400,"message":"Invalid input parameters","status":"error"}
Here is my code:
import requests
import json
api_url = "https://anlyticstts.com//api/insights/v1/reports"
headers = {
'Content-Type': 'application/json',
'X-access-key': 'e13168e9f1504d63455'
}
data = {
"search_term_ids": [60, 61],
"product_list_ids": [120],
"start_date": "20180801",
"end_date": "20180805",
"columns": {
"product": ["crawl_date", "product_name"],
"status": ["no_longer_available"],
"ranking": ["search_rank"],
"pricing": ["price"]},
"page_one_only": True, "format": "csv"
}
r = requests.post(url=api_url, data=data, headers=headers)
print(r.text)
You can try this sample code
import json
r = requests.post(api_url, data=json.dumps(data), headers=headers)
instead of
r = requests.post(url=api_url, data=data, headers=headers)
Related
I have created my own function which i import called timestamp, it returns two values :
from requests.auth import HTTPBasicAuth
import requests
import json
def timeframe():
response = requests.get("https://$host/api/profiler/1.13/reporting/timestamps.json", verify=False, auth=HTTPBasicAuth("admin", "admin"))
time = response.json()
for entry in time:
if entry.get('data_resolution') == 'min':
if entry.get('datasource') == 'FDS_TRAFFIC':
start_time = entry['start_time']
end_time = entry['end_time']
return start_time, end_time
timeframe()
i need to add timestamps to a keys in a json body request, you will see 'end' & 'start' keys. I need to retrieve those timestamps and somehow add them to those keys.
import requests
import timestamp
from requests.auth import HTTPBasicAuth
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
stamp = timestamp.timeframe()
print(stamp)
url = 'http://10.65.170.112/api/profiler/1.12/reporting/reports'
headers = {'Content-Type': 'application/json'}
payload = {
"criteria": {
"time_frame": {
"start": str(stamp[0]),
"end": str(stamp[1]),
"resolution": "flow"
},
"query": {
"realm": "traffic_flow_list",
"sort_column": 41,
"devices": [
{
"ipaddr": "10.65.170.2"
}
],
"group_by": "flw",
"columns": [
729,
40,
41,
14,
44,
10,
45,
46
]
}
},
"template_id": 184
}
req = requests.post(url, headers=headers, data = payload, verify=False, auth=HTTPBasicAuth('admin', 'admin'),)
print(req.status_code, req.text)
Not sure what to do.
Thanks
The function you created returns a tuple: return start_time, end_time.
So, a way to implement would be:
start, end = timestamp.timeframe()
Then, you can hydrate your body:
body = {
"criteria": {
"time_frame": {
"end": end,
"start": start,
"resolution": "flow"
},
import requests
import timestamp
from requests.auth import HTTPBasicAuth
import urllib3
import json
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
stamp = timestamp.timeframe()
auth = HTTPBasicAuth("admin", "admin")
url = "https://$host/api/profiler/1.13/reporting/reports"
headers = {'Content-Type': 'application/json'}
payload = {
"criteria": {
"time_frame": {
"start": stamp[0],
"end": stamp[1],
"resolution": "flow"
},
"query": {
"realm": "traffic_summary",
"sort_column": 41,
"devices": [{ "ipaddr": "10.65.170.2"}],
"group_by": "hos",
"columns": [
729,
40,
41,
14,
44,
10,
45,
46
]
}
},
"template_id": 184
}
req = requests.post(url, verify=False, auth=auth, headers=headers, data=json.dumps(payload))
print(req.headers)
Was resolved by adding data=json.dump(payload)
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
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"}}}]}'
I need to make a post into an API. I'm working with python. I'm new on this and I can't create an ad tag. I tried with create a dict with the api example information but it didn't work. When I run the >>> sitios_creados, the answer is ''
and when I run sites.status_codeI reveice `415.
I don't understand why because if you see in my code, I did a right post python requests before with the token
I must to take the publisherid and with it and the token id create the ad tag.
my publisherid is: 15663
my code:
import requests
import json
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ',
}
data = [
('grant_type', 'password'),
('username', ''),
('password', ''),
]
response = requests.post('http://api.site.com/v1/oauth/generateOauthToken', headers=headers, data=data)
json_data = json.loads(response.text)
token = json_data['access_token'].encode("utf-8")
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer {}'.format(token)
}
sites = requests.post('http://api.site.com/v1/inventorymgmt/publisherAdTag?entityId=15663', headers=headers, data=data)
sitios_creados = sites.content
Api information example:
URL: http://api.site.com/v1/inventorymgmt/publisherAdTag?entityId=2685
Method: POST
Request Body:
{
"publisherId": 2685,
"publisherSiteurl": "http://example.org",
"adTagName": "THIS_IS_TEST_DEMAND_5",
"adCodeTypeId": 1,
"foldPlacementId": 1,
"adTypeId": 3,
"pagePlacementId": 1,
"adExpansionDirectionId": 1,
"adSize": {
"name": null,
"width": 0,
"height": 0,
"id": 9
},
"adTagPlacements": [{
"adTagPlacementId": 0,
"linkOnlyToGeo": false,
"ecpm": 1,
"adScript": "THIS IS DEMO SCRIPT",
"currency": 1
}],
"adTagCustomParamMap": [{
"name": "kadcarrier",
"macroValue": "techno.carrier"
}, {
"name": "kadcity",
"macroValue": "geo.city"
}]
}
Is it an API for a website?
When yes, you can do a network analysis in the developer tool of your browser and copy the curl command of the POST package.
Then you surf to curl.trillworks.com and convert the curl command it into a Python POST request.
Inside of your python request you can modify the values.