I am new to python & POST message.
I am trying to call an API with JSON POST message and expecting a JSON response but my initial code not able to make the call as required .
using the URL,Headers & Postdata in chrome browser POST extension works fine.
#!/usr/bin/python
import requests
import json
url = 'http://xxxxx:111/batches'
postdata = {
"active": "true",
"size": "2",
"ctr": {
"user": "Admin",
"id": "1234"}}
#headers = {'content-type': 'application/json',
#'Authorization': 'Basic xyz879jjkhhnm',
#'Accept-Encoding': '0'}
headers = {'Authorization': 'Basic xyz879jjkhhnm', 'Accept-Encoding': '0'}
print headers
post_call = requests.post(url, headers=headers, data=json.dumps(postdata))
print post_call, "POST call"
print post_call.text, "TEXT"
print post_call.content, "CONTENT"
post_call.status_code, "STATUS CODE"
Error:
{'Accept-Encoding': '0', 'Authorization': 'Basic xyz879jjkhhnm'}
<Response [500]> POST call
[{"code":"server_error","description":"com.sun.jersey.api.MessageException: A message body reader for Java class com.hide.cpn.rest.v1.entity.CouponCodeBatchResourceEntity,
and Java type class com.hide.cpn.rest.v1.entity.CouponCodeBatchResourceEntity, and MIME media type application/octet-stream was not found.
\nThe registered message body readers compatible with the MIME media type are:\napplication/octet-stream ->\n
com.sun.jersey.core.impl.provider.entity.ByteArrayProvider\n com.sun.jersey.core.impl.provider.entity.FileProvider\n
com.sun.jersey.core.impl.provider.entity.InputStreamProvider\n com.sun.jersey.core.impl.provider.entity.DataSourceProvider\n
com.sun.jersey.core.impl.provider.entity.RenderedImageProvider\n*/* ->\n com.sun.jersey.core.impl.provider.entity.FormProvider\n
com.sun.jersey.core.impl.provider.entity.StringProvider\n com.sun.jersey.core.impl.provider.entity.ByteArrayProvider\n
com.sun.jersey.core.impl.provider.entity.FileProvider\n com.sun.jersey.core.impl.provider.entity.InputStreamProvider\n
com.sun.jersey.core.impl.provider.entity.DataSourceProvider\n com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General\n
com.sun.jersey.core.impl.provider.entity.ReaderProvider\n com.sun.jersey.core.impl.provider.entity.DocumentProvider\n
com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader\n com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader\n
com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader\n com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General\n
com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General\n com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General\n
com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General\n com.sun.jersey.core.impl.provider.entity.EntityHolderReader\n
com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General\n com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General\n
com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy\n","errorValues":null}] TEXT
**Edit:1 (changing Headers seems to get ridoff Java error now ,but getting below error now)**
headers = {'Authorization': 'Basic xyz879jjkhhnm', 'Accept-Encoding': '0', 'content-type': 'application/json'}
New error:
{'content-type': 'application/json', 'Accept-Encoding': '0', 'Authorization': 'Basic xyz879jjkhhnm'}
<Response [400]> POST call
[{"code":"invalid_attribute_of_request","description":"Attribute value type is not Integer. actual value = (\"2\")","errorValues":null,"field":"size"}] TEXT
[{"code":"invalid_attribute_of_request","description":"Attribute value type is not Integer. actual value = (\"2\")","errorValues":null,"field":"size"}] CONTENT
Ok,as per the latest change Header change in (EDIT 1) i had to remove the double quotes from post data "SIZE",that solved my error.
headers = {'Authorization': 'Basic xyz879jjkhhnm', 'Accept-Encoding': '0', 'content-type': 'application/json'}
postdata = {
"active": "true",
"size": "2", --> Changed to "size": 2,
"ctr": {
"user": "Admin",
"id": "1234"}}
Related
My audio for podcast and art for it on google drive, in doc says to make like this, but it returns 400 error
import requests
podcast_file = "https://drive.google.com/file/d/1w0IDXVotyHKEGSbBWUxEoDvaJQRsWCJO"
headers = {
'Authorization': 'Token here my token',
'Content-Type': 'application/json',
}
new_episode = {
"title":"Too many or too few?",
"description":"",
"summary":"",
"artist":"Muffin Man",
"tags":"",
"duration":23462,
"guid":"Buzzsprout788880",
"episode_number":1,
"season_number":1,
"explicit":False,
"private":False,
"email_user_after_audio_processed": False,
"audio_url": podcast_file,
"artwork_url": "https://drive.google.com/file/d/1xoNKAbTYX8GjVg0ZB_ekFUl8ljQICMZv"
}
url = 'https://www.buzzsprout.com/api/episodes.json'
req = requests.post(url, data=new_episode, headers=headers)
print(req.text)
print(req.status_code)
I am new to rest api. I am trying to post data to service. recently I am doing it through postman tool and it's working.
Now I want to do it using python so I am copying postman's python code it's working, but is there any other way to send data using python
like here my python script
import requests
url = "http://http:/localhost:3200/api/log"
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"ip\"\r\n\r\n235.23.14.242\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n{\n\t\t\"Main\": \n\t\t{\n\t\t \"subfolder\" : \n\t\t\t{ \n\t\t\t \"photos\" : \n\t\t\t\t{\n\t\t\t\t \"January\" : \n\t\t\t\t\t[\n\t\t\t\t\t\t\"name Detail of photo\",\n\t\t\t\t\t\t\"date id of photo\",\n\t\t\t\t\t\t\"location location detail\"\n\t\t\t\t\t],\n\t\t\t\t \"February\" : \n\t\t\t\t\t[\n\t\t\t\t\t\t\"name Detail of photo\",\n\t\t\t\t\t\t\"date id of photo\",\n\t\t\t\t\t\t\"location location detail\"\n\t\t\t\t\t]\n\t\t\t\t}\n}\n}\n}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
'cache-control': "no-cache",
'Postman-Token': "5466e12e-b5d8-4326-a75c-8c9502963ed5"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
this code is working but here I have to put json data in payload . can I do it other way ?? like load json file in string and pass that string in payload . Actually I tried it but it's not working like this
import requests
url = "http://http:/localhost:3200/api/log"
str="235.23.14.242"
files={
"Main":
{
"subfolder" :
{
"photos" :
{
"January" :
[
"name Detail of photo",
"date id of photo",
"location location detail"
],
"February" :
[
"name Detail of photo",
"date id of photo",
"location location detail"
]
}
}
}
}
payload = {"ip":str,"file":files}
headers = {
'content-type': "multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW",
'cache-control': "no-cache",
'Postman-Token': "5466e12e-b5d8-4326-a75c-8c9502963ed5"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
Is there any other way to send this type of data ???
finally I found ans...
import requests
url = "http://http:/localhost:3200/api/log"
strr="235.23.14.242"
files={
"Main":
{
"subfolder" :
{
"photos" :
{
"January" :
[
"name Detail of photo",
"date id of photo",
"location location detail"
],
"February" :
[
"name Detail of photo",
"date id of photo",
"location location detail"
]
}
}
}
}
fl=str(files)
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; " \
"name=\"ip\"\r\n\r\n"+strr+"\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; " \
"name=\"file\"\r\n\r\n"+fl+"\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW",
'cache-control': "no-cache",
'Postman-Token': "5466e12e-b5d8-4326-a75c-8c9502963ed5"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
Thanks for response..
I am sending a JSON post request to a URL with headers and para:
headers = {
'channel':'mobiApp',
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': '939',
'Cookie': 'xyzxcasd',
'User-Agent': 'okhttp/3.8.0'
}
url = 'https://api.xyz.com/account.jsp'
data = {'act':'login','class':'profile','prftcf':code1,'p':password1,'u':username1,'ver':'0.9.1'}
content = json.dumps(data)
print ("")
print (content)
print ("")
r = requests.post(url,headers=headers,data=content,allow_redirects=True)
z = r.text
(above is the request I am sending)
I am getting this as response:
{
"s": 0,
"err": "",
"errCode": "",
"status": "",
"ccnt": 1,
"em": "blueyes81382#yahoo.com",
"pid": "2436999645",
"bvUserToken": "ee936b7065353389878696fc7cc4d71a646174653d3230313730393137267573657269643d32343336393939363435"
}
What I want to do is redirect after this post request (if bvUSertoken exists) to some URL, i.e.: https://api.xyz.com/acount/summary, and print the response.
okay so i found a solution to this
p['Set-cookie'] parse cookie from previous response header
cookies = (p['Set-Cookie'])
headers1 = {
'channel':'mobiApp',
'Content-Type': 'application/json; charset=UTF-8',
'Cookie' : cookies,
'User-Agent': 'okhttp/3.8.0'
}
url = 'your redirect url'
urlx = url
parsing = requests.get(urlx,headers=headers1)
trying to replicate a cURL request to an appliance API with python Requests
curl -qgsSkH "Content-Type: multipart/form-data"
--no-progress-bar
--header "X-Api-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
-F "filename=#cygdrive/c/tmp/test.txt"
-F "options={\"application\":\"2\",\"timeout\":\"500\",\"priority\":\"0\",
\"profiles\":[\"win7-sp1\"],\"analysistype\":\"0\",\"force\":\"true\",
\"prefetch\":\"0\"}"
https://xxx.xxx.xxx.xxx:443/apis/v1.1.0/submissions
I have succefully authenticated to the API and can use the recieved token in the POST request. My current python function is shown below.
def api_file_submit(api_token, file_name):
login_headers = {'X-Api-Token': api_token, 'Accept': 'application/json', 'Content-Type': 'multipart/form-data'}
files = {"filename": open(file_name, 'rb')}
sub_options = {"application": "-1", "timeout": "240", "priority": "0", "profiles": ["Win7 Sp1"],
"analysistype": "0", "force": "false", "prefetch": "value"}
j = simplejson.dumps(sub_options)
data = {'options': j}
r = requests.post(api_submit, headers=login_headers, files=files, data=data, verify=False)
print "REQUEST HEADER: " + str(r.request.headers)
print "REQUEST BODY: " + str(r.request.body)
print "RESPONSE HEADER: " + str(r.headers)
print "RESPONSE CONTENT: " + str(r.content)
print "RESPONSE STATUS: " + str(r.status_code)
print "RESPONSE REASON: " + str(r.reason)
return
The API returns a HTTP 400, Bad Request when attempting to POST. below are the results of the function
REQUEST HEADER: {'Content-Length': '424', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'application/json', 'User-Agent': 'python-requests/2.11.1', 'Connection': 'keep-alive', 'X-Api-Token': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'multipart/form-data'}
REQUEST BODY: --63a06536e02c4479a846c5fe320cdf7f
Content-Disposition: form-data; name="options"
{"force": "false", "profiles": ["Win7 Sp1"], "priority": "0", "application": "-1", "prefetch": "value", "timeout": "240", "analysistype": "0"}
--63a06536e02c4479a846c5fe320cdf7f
Content-Disposition: form-data; name="filename"; filename="test.vbs"
x = msgbox("this is an test file", 0, "test file")
--63a06536e02c4479a846c5fe320cdf7f--
RESPONSE HEADER: {'Content-Length': '257', 'Expires': '0', 'Connection': 'close', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Date': 'Fri, 24 Mar 2017 17:11:47 GMT', 'X-Frame-Options': 'DENY', 'Content-Type': 'application/json;charset=ISO-8859-1'}
RESPONSE CONTENT: {"apis":{"#version":"v1.1.0","description":"Error parsing options, please check you have provided a file for upload and included 'options' in json format as part of request","errorCode":"BESUB1001","httpStatus":400,"message":"Could not parse input"}}
RESPONSE STATUS: 400
RESPONSE REASON: Bad Request
Process finished with exit code 0
What am I missing to properly format the request and submit the file, replicating the cURL request above?
opened the file, not as a dictionary, just got the handle
formatted options as JSON, and included in the "files"
def api_file_submit(api_token, file_name):
login_headers = {'X-Api-Token': api_token, 'Accept': '*/*'}
files = open(file_name, 'rb')
sub_options = {'application': '0', 'timeout': '240', 'priority': '0', 'profiles': ['win7-sp1'], 'analysistype': '2', 'force': 'false', 'prefetch': '1'}
submissionData = ('', json.dumps(sub_options), 'application/json')
files = {'options': submissionData, 'filename': files}
r = requests.post(api_submit, headers=login_headers, files=files, verify=False)
I'm trying to import contacts into a contact list in Qualtrics. I am using python to do this.
Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
data = open('contacts.json', 'rb')
headers = {'X-API-TOKEN': Token, 'Content-Type':'application/json',}
r = requests.post('https://az1.qualtrics.com/API/v3/mailinglists/' + ContactsID +'/contactimports', headers=headers, data=data)
r.text
This code gives me the following error: '{"meta":{"httpStatus":"400 - Bad Request","error":{"errorMessage":"Invalid Content-Type. expected=multipart/form-data found=application/json","errorCode":"RP_0.1"},"requestId":null}}'
I changed the content type to multipart/form-data that it says it is expecting and received the response "413", which qualtrics explains means "The request body was too large. This can also happen in cases where a multipart/form-data request is malformed."
I have tested my json and verified that it is valid. Also, I don't know why the request body would be too large because it's only 13 contacts that I'm trying to import. Any ideas?
With the help of Qualtrics Support, I was eventually able to get the following code to work:
Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
url = "https://az1.qualtrics.com/API/v3/mailinglists/" + ContactsID + "/contactimports/"
headers = {
'content-type': "multipart/form-data; boundary=---BOUNDRY",
'x-api-token': "Token"
}
files = {'contacts': ('contacts', open('contacts.json', 'rb'), 'application/json')}
request = requests.post(url, headers=headers, files=files)
print(request.text)
Please note that if you want to use this code, you will need to change "az1" in the URL to your own Qualtrics datacenter ID.
You need to use files = .. for a multipart request:
Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
data = open('contacts.json', 'rb')
headers = {'X-API-TOKEN': Token}
r = requests.post('https://az1.qualtrics.com/API/v3/mailinglists/' + ContactsID +'/contactimports',files={"file":data}, headers=headers)
r.text
Once you do requests will take care of the rest:
In [36]: url = 'http://httpbin.org/post'
In [37]: headers = {'X-API-TOKEN': "123456789"}
In [38]: files = {'file': open('a.csv', 'rb')}
In [39]: r = requests.post(url, files=files, headers=headers)
In [40]: print r.text
{
"args": {},
"data": "",
"files": {
"file": "a,b,c\n1,2,3"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "152",
"Content-Type": "multipart/form-data; boundary=3830dbe5fa6141f69d3d85dee4ba6e78",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0",
"X-Api-Token": "123456789"
},
"json": null,
"origin": "51.171.98.185",
"url": "http://httpbin.org/post"
}
In [41]: print(r.request.body)
--3830dbe5fa6141f69d3d85dee4ba6e78
Content-Disposition: form-data; name="file"; filename="a.csv"
a,b,c
1,2,3
--3830dbe5fa6141f69d3d85dee4ba6e78--
looking at the docs, you actually want something closer to:
Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
data = open('contacts.json', 'rb')
files = {'file': ('contact', data ,'application/json', {'X-API-TOKEN': Token})}
r = requests.post('https://az1.qualtrics.com/API/v3/mailinglists/' + ContactsID +'/contactimports',files=files)