How do i post python varaibles using curl? - python-3.x

for instance i have the following
title = "some title"
name = "name"
headers = {
'Content-Type': 'application/json',
}
data = '{"title": title,"name":name,"action":"save"}'
response = requests.post('http://192.168.1.7:8080/news/save.json', headers=headers, data=data)
i want to post the title and the name to a database with those fields, and they both will keep on changing .
I execute this statement and it works without any errors, but when i see my database, these fields arent there yet.
If i hardcode the title and the name then it works fine.

Not sure what does this have to do with curl
You are sending an hardcoded string that has nothing to do with the defined variables. You should create a json and send that:
import json
title = "some title"
name = "name"
headers = {
'Content-Type': 'application/json',
}
data = json.dumps({"title": title, "name": name, "action":"save"})
response = requests.post('http://192.168.1.7:8080/news/save.json',
headers=headers, data=data)

Related

PowerQuery (Excel) - POST rest api webservice call - fail get contents (500): internal server error

I try to call a webservice (sap business one) to login, so I can obtain a session id.
I try to use the following:
let
url = "https://WEB/b1s/v1/Login",
headers = [#"Content-type"="application/json", #"Connection"="keep-alive"],
postData = Json.FromValue([CompanyDB = "Company", Password = "12345", UserName = "test"]),
response = Web.Contents(
url,
[
Headers = headers,
Content = postData
]
),
jsonResponse = Json.Document(response)
in
jsonResponse
This gives me the response described in the title.
Now when I did obtain a session id and manually cal for a get request on the same I do get a result (eg.):
let
url = "https://WEB/b1s/v1/Items?$select=ItemCode,ItemName",
headers = [#"Prefer"="odata.maxpagesize=0", #"Cookie"="B1SESSION=1bba9408-dd9e-11ec-8000-000d3a83435c; ROUTEID=.node1"],
response = Web.Contents(
url,
[
Headers = headers
]
),
jsonResponse = Json.Document(response),
value = jsonResponse[value],
[...]
This gives the list of items as a result.
Doing all of the above in Postman returns a proper result. I would expect this out of the "LOGIN":
{
"odata.metadata": "https://WEB/b1s/v1/$metadata#B1Sessions/#Element",
"SessionId": "7c01d84a-dda2-11ec-8000-000d3a83435c",
"Version": "1000141",
"SessionTimeout": 30
}
Any idea what else I can try?
Cheers and thank you
Andreas

How to write the correct recipe for an HTTP POST request on Groovy

I'm trying to write a recipe for an HTTP POST request in Groovy and the way I am doing it is by editing a previous recipe but adjusting it to my own needs:
Set two request properties (Content-Type: application/json, Authorization: Bearer xxxxx)
Set raw data (json) ({"var_1": "value 1", "var_2": "value 2"})
The recipe I'm trying to modify is
def baseUrl = new URL('http://some.url.com/')
def connection = baseUrl.openConnection()
connection.with {
doOutput = true
requestMethod = 'POST'
setRequestProperty = ['Content-Type': 'application/json', 'Authorization': 'Bearer xxxx']
outputStream.withWriter { writer ->
writer
}
println content.text
}
At first when executing the script I get the following error:
Exception thrown
java.io.IOException: Server returned HTTP response code: 401 for URL: http://some.url.com/
The other thing is that I don't know how to add the need (2) to the script.
Thanks in advance.
Based on Javadoc I would put the code like so:
def baseUrl = new URL('http://some.url.com/')
def connection = baseUrl.openConnection()
connection.with {
doOutput = true
requestMethod = 'POST'
addRequestProperty 'Content-Type', 'application/json'
addRequestProperty 'Authorization', 'Bearer xxxx'
outputStream.withWriter{ it << '{"var_1": "value 1", "var_2": "value 2"}' }
println content.text
}

How to send POST request after form submit 302 in Django?

I have an implementation as follows:
There is a payment form wherein user fills all the details.(API1), here I'm getting an error 302:
On submit of that form one of the function in my views is called.
In the backend implementation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2)
But the problem is coming as the request is going as GET and hence it is dropping all the form data I'm sending along with the request.
Following is the code.
views.py -->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
content = response.url
return_config = {
"type": "content",
"content": redirect(content)
}
return return_config
How do I send the 2nd request(API2) as POST request along with all parameters? What am I doing wrong here?
Thank you for your suggestions.
If the requests returns a 302 status, the new url is available in response.headers['Location']. You can keep following the new url, till you end up with a valid response.
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
while response.status_code == 302:
response = requests.post(response.headers['Location'], data=payload_encoded, headers=headers)
content = response.text
return_config = {
"type": "content",
"content": content
}
return return_config
# here you are assigning the post url to content ie. 'https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****'
content = response.url
return_config = {
"type": "content",
"content": redirect(content) # calling redirect with the response.url
}
change to:
# check status code for response
print(response)
content = response.json() # if response is of json in format
content = response.text # if response is of plain text
return_config = {
"type": "content",
"content": content
}
return return_config
request.post() returns requests.Response object. inorder to get the response data you need to access it using .text or .json() depending on the format in which the response is sent.

Create variable string for request API payload

I have a list of URLs that all refer to images. I want to loop through the list and call a face recognition API that accepts these URLs. To call the API, I need to provide the payload dictionary. However, the example code from the API requires the following form for the payload dictionary:
payload = "{\"url\":\"https://inferdo.com/img/face-3.jpg\",\"accuracy_boost\":3}"
The URL in this example payload dictionary would look like this in my list:
list_of_urls = ["https://inferdo.com/img/face-3.jpg", ...]
How can I insert the entries of my list into the payload dictionary with a for loop?
I tried to use a "regular" payload dictionary, but it did not work:
for url_path in list_of_urls:
payload = {'url' : url_path,'accuracy_boost':3}
I went to the API documentation and found you need to send the payload as JSON. Something like this will do the job:
import requests
import json
endpoints = {
'face': 'https://face-detection6.p.rapidapi.com/img/face'
'face_age_gender': 'https://face-detection6.p.rapidapi.com/img/face-age-gender'
}
urls = [
'https://inferdo.com/img/face-3.jpg'
]
headers = {
'x-rapidapi-host': 'face-detection6.p.rapidapi.com',
'x-rapidapi-key': 'YOUR-API-KEY',
'content-type': 'application/json',
'accept': 'application/json'
}
for url in urls:
payload = {
'url': url,
'accuracy_boost': 3
}
r = requests.post(
endpoints.get('face'), # or endpoint.get('face_age_gender')
data=json.dumps(payload),
headers=headers
)
if r.ok:
# do something with r.content or r.json()
I hope it helps.

Multipart form post, csv and param python

Im having difficulty with the following code:
payload = {
'file' : ('csvtest.csv', open('csvtest.csv', 'rb')),
'parser' : '{"name":"CSV","displayName":null,"description":"Supports delimited text files with a field delimiter and optional escape and quote characters.","shortDescription":null,"properties":[{"name":"Auto Detect?","displayName":"Auto Detect?","value":"true","values":null,"placeholder":"","type":"select","hint":"Auto detect will attempt to infer delimiter from the sample file.","objectProperty":"autoDetect","selectableValues":[{"label":"true","value":"true","hint":null},{"label":"false","value":"false","hint":null}],"required":false,"group":"","groupOrder":1,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_0"},{"name":"Header?","displayName":"Header?","value":"true","values":null,"placeholder":"","type":"select","hint":"Whether file has a header.","objectProperty":"headerRow","selectableValues":[{"label":"true","value":"true","hint":null},{"label":"false","value":"false","hint":null}],"required":false,"group":"","groupOrder":2,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_1"},{"name":"Delimiter Char","displayName":"Delimiter Char","value":",","values":null,"placeholder":"","type":"string","hint":"Character separating fields","objectProperty":"separatorChar","selectableValues":[],"required":false,"group":"","groupOrder":3,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_2"},{"name":"Quote Char","displayName":"Quote Char","value":"\'","values":null,"placeholder":"","type":"string","hint":"Character enclosing a quoted string","objectProperty":"quoteChar","selectableValues":[],"required":false,"group":"","groupOrder":4,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_3"},{"name":"Escape Char","displayName":"Escape Char","value":"\\\\","values":null,"placeholder":"","type":"string","hint":"Escape character","objectProperty":"escapeChar","selectableValues":[],"required":false,"group":"","groupOrder":5,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_4"}],"objectClassType":"com.thinkbiganalytics.discovery.parsers.csv.CSVFileSchemaParser","objectShortClassType":"CSVFileSchemaParser","propertyValuesDisplayString":null,"supportsBinary":false,"generatesHiveSerde":true,"tags":["CSV","TSV"],"clientHelper":null,"allowSkipHeader":true,"groups":[{"group":"","layout":"column","properties":[{"name":"Auto Detect?","displayName":"Auto Detect?","value":"true","values":null,"placeholder":"","type":"select","hint":"Auto detect will attempt to infer delimiter from the sample file.","objectProperty":"autoDetect","selectableValues":[{"label":"true","value":"true","hint":null},{"label":"false","value":"false","hint":null}],"required":false,"group":"","groupOrder":1,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_0"},{"name":"Header?","displayName":"Header?","value":"true","values":null,"placeholder":"","type":"select","hint":"Whether file has a header.","objectProperty":"headerRow","selectableValues":[{"label":"true","value":"true","hint":null},{"label":"false","value":"false","hint":null}],"required":false,"group":"","groupOrder":2,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_1"},{"name":"Delimiter Char","displayName":"Delimiter Char","value":",","values":null,"placeholder":"","type":"string","hint":"Character separating fields","objectProperty":"separatorChar","selectableValues":[],"required":false,"group":"","groupOrder":3,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_2"},{"name":"Quote Char","displayName":"Quote Char","value":"\'","values":null,"placeholder":"","type":"string","hint":"Character enclosing a quoted string","objectProperty":"quoteChar","selectableValues":[],"required":false,"group":"","groupOrder":4,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_3"},{"name":"Escape Char","displayName":"Escape Char","value":"\\\\","values":null,"placeholder":"","type":"string","hint":"Escape character","objectProperty":"escapeChar","selectableValues":[],"required":false,"group":"","groupOrder":5,"layout":"column","hidden":false,"pattern":"","patternInvalidMessage":"Invalid Input","formKey":"property_4"}]}],"editable":true}'
}
headers = {
'accept': "application/json",
'authorization': "Basic ZGxhZG1pbjp0aGlua2JpZw==",
'cache-control': "no-cache",
}
url = "http://localhost:8400/proxy/v1/schema-discovery/hive/sample-file"
req = requests.post(url, data=payload, headers=headers)
print(req.text)
For some reason im getting the error "HTTP 415 Unsupported Media Type".
I'm trying to send a csv, along with some json in a multipart form. I originally had this working with http.client but the way I was doing it it was adding extra line breaks and carriage return literals into the multipart message body.
Any help greatly appreciated!
The issue I couldnt originally see was with declaring the file type in the file tuple, shown below as 'text/csv' in the solution.
import http.client
file = { 'file' : ('csvtest.csv', open('csvtest.csv', 'rt'), 'text/csv') }
payload = { 'parser' : '{object trimmed for comment}' }
headers = { 'accept': "application/json", 'authorization': "Basic ZGxhZG1pbjp0aGlua2JpZw==", }
url = "http://localhost:8400/proxy/v1/schema-discovery/hive/sample‌​-file"
req = requests.post(url, data=payload, files=file, headers=headers)
pprint(req.text)

Resources