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..
Related
I'm trying to send a POST and I get this error:
{"data":null,"error":{"status":400,"name":"ValidationError","message":"Missing "data" payload in the request body","details":{}}}
In [ ]:
This is my code:
import requests
import json
myToken = '256e8f598edc0990b39dbfe8c4acf39ec83ee3a1a8f212a7656b3892585755c52857503a356ed003fa6b1f5f4b89fc34b0aa64000bb1bf5bba75257a0128365c75aa96a8cb4ed7a32e7fc7b5ec899ae6d2633a7004ef7f991b8ca6e6bdac4a3a75954425f95cc1a209e09272b5582f58690759f81aecb506070c3c19b3cdac2f'
myUrl = 'http://localhost:1337/api/countries'
head = { 'Authorization': 'Bearer {}'.format(myToken), 'Content-Type': 'application/json'}
session = requests.Session()
session.headers.update(head)
Get request & response (working well):
response = session.get(myUrl)
print (response.text)
{
"data":[
{
"id":1,
"attributes":{
"name":"United States",
"createdAt":"2022-04-09T04:15:13.925Z",
"updatedAt":"2022-04-09T04:15:15.226Z",
"publishedAt":"2022-04-09T04:15:15.220Z"
}
}
],
"meta":{
"pagination":{
"page":1,
"pageSize":25,
"pageCount":1,
"total":1
}
}
}
Post request & response:
data = json.dumps(['data', {'name': 'United States'}])
response = session.post(myUrl, data = data)
print (response.text)
{
"data":null,
"error":{
"status":400,
"name":"ValidationError",
"message":"Missing \"data\" payload in the request body",
"details":{
}
}
}
Thanks in advance
I did the solution for that,
First of all: I changed the "data" to "json"
data = {'data': {'name': 'United states'}}
request = session.post(myUrl, json = data)
print (request.text)
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)
I am new to http requests and trying to automate some work. But I am unable to get the required result. I have looked many posts and documentation of python requests module but there is no change in the result.
Code I wrote
def installFont():
print "Installing font"
urlToHit = "some http address"
header_ = { "UserID": "00000", "PortalName": "EDC", "ModifyBy" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type" : "application/json"}
body_ = {
"Email": "abc#xyz.com",
"AssetLicenseType": "Trial",
"MachineIds": ["machine1", "machine2"],
"fontAsset":
[
{
"FontId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"FontName": "Neue Aachen™ Pro Ultra Light",
"FontUrl": "http://helveticaurl",
"FontDownloadUrlAPI": "url",
"FontDownloadUrl" : "url1,
"FontFamilyName": "Neue Aachen™ Pro",
"FontFamilyUrl": "http://FontFamilyUrl",
"FontStyle": "Normal",
"FontWeight": "100",
"ExpiryDate": "2017-2-27 11:17:01",
"FontFamilyId": "34"
}
]
}
r = requests.request("POST", urlToHit, data=body_, headers=header_)
print r.headers
print r.status_code
print r.text
Itried same thing with postman which gives me correct result but via python I am getting output as
{'X-Processing-Time-Milliseconds': '3', 'Transfer-Encoding': 'chunked', 'X-Powered-By': 'ASP.NET', 'Server': 'Kestrel', 'Date': 'Mon, 06 Feb 2017 14:51:59 GMT', 'Content-Type': 'application/json'}
400
{"Message":"''"}
I think I am doing some mistake while passing body_ in
r = requests.request("POST", urlToHit, data=body_, headers=header_)
Output via postman
{"Message":"Created Successfully","SuccessCount":2,"FailCount":0}
You need to use:
r = requests.post(urlToHit, json=body_, headers=headers_)
Please go through the documentation.
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"}}
I have the following cookie, stored as a dict:
cookies = session.cookies.get_dict()
{'nflx-rgn': '"ue1|1433799654706|uw2:2"', 'SecureNetflixId': 'v%3D2%26mac%3DAQEAEQABABTh6lNR0cbOgGRD7DT7CChBIhA83qsfV_k.%26dt%3D1433799654968', 'memclid': '9a55d2c6-4d85-44bb-8338-0b1a180a7c44', 'NetflixId': 'v%3D2%26ct%3DBQAOAAEBEFP07qwktIitvHYO-Xn6gU2BYKymzutSFtIyfD_zEWVo4yMjbjJ4LgPmtZhjgE5lRWg5OTP8C1N2zNbTc8VsdzUS3OaLnsGsV4AkXZzkewt0X0WcMwSYVl3-pX8Rs0jH2PCXixD8K2oARmtQIrWCvv35EUOpGCb3v-tExqpZaN_6FBfTrF68FXcR4kDGAjXYooBWKnCv1aS1VVscso_GRg6HH7--qOsjW7WoPkxyRAAqt0GmeD8tY5aQHMbD779s7oiAr7YArEmUC_3Hdej0huyGo0Iq-_IlY_jGZhyupIO0ZIpznvGB2teF8YeaiSh2LlQ4RIlUOo3hO5n9lmlmBnRXAYGYbJ_64HiwTfsw3jRWkgAJWnnxSHo9sGLJibspLCQ3RzdA-JwxSPYoBh-HkhnAxxPveWmPbH_1JtXR9rvhfnenIhDgzu_nCUH7i-sxg4bnKhGjpVzH1Y8x9wSNE2-xWdax912FBEzQWyT5I2HxnQQ.%26bt%3Dusr%26ch%3DAQEAEAABABRxRbrqqSNQFSxPcuqeaLCNvVMfYe40K6A.%26mac%3DAQEAEAABABTQs51fmHZefZn26dZQFm9ZDMjlNgmXis8.', 'tlr': 'US|1433799655947'}
How would I then add that to my requests header so it would be valid. For example:
headers = {
"Accept-Language" : "en-US,en;q=0.8,pt;q=0.6",
"Connection" : "keep-alive",
"Cookies": ???
}
requests.get(url, headers=headers)
I would prefer to do this over adding in the cookies argument to requests.
Use this:
cookie_string = "; ".join([str(x)+"="+str(y) for x,y in cookies.items()])
headers = {
"Accept-Language" : "en-US,en;q=0.8,pt;q=0.6",
"Connection" : "keep-alive",
"Cookies": cookie_string
}
requests.get(url, headers=headers)