Post request error: Missing or Invalid Post Body - python-3.x

I'm getting the following error and I'm not sure why:
{"success":false,"errors":["Missing or invalid POST body."],"results":[]}
I'm not sure if there is a problem with how I have my code structured, sending bad json, or what. If you could give me an idea of where to troubleshoot this, that would be great. Thanks. Here is how I have my settings:
headers = {
"Accept": "application/json",
"Authorization": "bearer " + bearer_token,
"Content-Type": "application/json",
}
data = {
'limit':10,
'sort':"MinPrice DESC",
'filters':[
{
'name':'SetName',
'values':'All'
}
]
}
url = 'http://api.tcgplayer.com/V1.9.0/catalog/categories/3/search'
def catalog_data():
r = requests.post(url, headers=headers, data=data)
print(r.text)
catalog_data()

Making the change from data=data to json=data allowed my Post data to be read properly.

Related

Is there a way to remove the default headers from the uploaded file when we post a file using a PUT request

I have a simple put request for to upload a file to an API using a post request.
api_key = "Auth token"
request_headers = {
"Authorization": "Bearer {}".format(api_key),
"Accept": "*/*",
"Content-Type": "text/plain",
}
url = "https://graph.microsoft.com/v1.0/sites/vmt8c.sharepoint.com,01f460f4-3c8a-470d-ace6-4058b2c78952,3589d1c5-e699-45a0-b8ab-1027175c367f/drive/items/root:/test-folder/aaa/test2.txt:/content"
files = {"my_file": open("params.yml", "rb")}
res = requests.put(url, files=files, headers=request_headers)
params.yml contains:
Hello! This is a test.
The uploaded data I get in /test-folder/aaa/test2.txt :
--222e00b3de068a0895a4f0f4bbd8a992
Content-Disposition: form-data; name="my_file"; filename="my_file"
Hello! This is a test
--222e00b3de068a0895a4f0f4bbd8a992--
I would like to get only "Hello! This is a test" in the uploaded data and remove the headers and everything else.
I tried a few approaches but couldn't succeed. Please help on this.

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
}

Google Oaut2 - Python using requests whiout Library

I am trying to authenticate not google by means of requests if I use the api but I don't know what I put in the "code" field and it will work, you can help me, or the code follows below.
import requests
url = "https://accounts.google.com/o/oauth2/token"
payload='grant_type=authorization_code&client_secret=xxxxx&client_id=xxxx&redirect_uri=https%3A%2F%2Fpushsistemas.com.br%2F&code='
headers = {
'content-type': 'application/x-www-form-urlencoded',
'Cookie': 'NID=219=RgUebbUM4k3WX0uQr8HVcIZkQ5-rMrb4HHnfnRzNTxUse776sG6-LItgXwpdv-MmaFYf3Tu4otJN-UfP70OzDtdnfam2dwAZkd6yMsr8BW_7lGE4FTaas9QkoG-hOMqXgYEHvI4YK39dWgXhWnL0E5LcsOv0DXnfjJ2kUf7VlTs; __Host-GAPS=1:jGXTa0ipDEC58oJF7pZwNBVeSXCQRw:3IRHy3GC9mAq4nqt'
}
response = requests.request("POST", url, headers=headers, data=payload)
This output
{
"error": "invalid_request",
"error_description": "Missing required parameter: code"
}
if it is not possible to do this way could you send me how to do it using the google library?

pisignage API login error: "This username/email is not registered or active"

From there api docs, I have created a request to login and get the token. The code is under below, it returns 401 . The credentials are right and I can log in from web, but through API I can not.
import requests
import json
params_dict = {
"email": "example#mail.com",
"password": "example",
"getToken": True
}
response = requests.post(
'https://example.piathome.com/api/session',
data=params_dict
# headers={'Content-type': 'application/json', 'accept': 'application/json'} returns 500
)
json_response = response.json()
print(json_response)
Make sure that the API endpoint is set to username.pisignage.com (not just pisignage.com).
And the headers are absolutely required. Request and Response types must be set to application/json.

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