I am trying to make a request for a form-data type. The request worked previously when it was just two files being used for the request. However, now an ID has to be inputted in the request also, and it won't work.
I have tried lots of different options of trying to get this to work, the ID is an input in a separate file, same as 'file_a' and 'file_b'. However, it is erroring with the ID form data field.
url = url
headers = {"Authorization": Access_token}
files = [('file_a', open(file_a, 'rb')), ('file_b', open(file_b, 'rb')), ('ID', ID)]
response = requests.post(url=url, files=files, headers=headers)
print(response.content)
I am expecting a response json string, however getting no response as the request is not working due to the ID integer field.
From your code sample, it seems ID is a file, but you probably want to pass it as form-encoded data to data argument in requests.post.
To do this create a dictionary containing the name of the field and its value:
url = url
headers = {"Authorization": Access_token}
files = [('file_a', open(file_a, 'rb')), ('file_b', open(file_b, 'rb'))]
data = {'ID', ID} # here's ID value
response = requests.post(url=url, files=files, headers=headers)
print('status code:', response.status_code)
Here you can find the documentation you need to send form data.
Please, let me know whether this helps you or if you need further help.
Related
I'm having a problem with a Python request, where I pass the body url to the API data.
Note: I have a Node.js project with TypeScript that works normally, prints to the screen and returns values. However if I try to make a request in Python it doesn't work with an error 401.
Below is an example of how the request is made in Python. can you help me?
import requests
url = 'https://admins.exemple'
bodyData = {
'login': 'admins',
'pass': 'admin',
'id': '26' }
headers = {'Content-Type': 'application/json'}
resp = requests.post(url, headers=headers, data=bodyData)
data = resp.status_code
print(data)
Please dump a dict to a json string as follows:
import json
resp = requests.post(url, headers=headers, data=json.dumps(bodyData))
You also can pass your dict to json kwarg
resp = requests.post(url, headers=headers, json=bodyData)
It will set Content-Type: application/json and dump dict to json automatically
You are not correctly authenticating with the server. Usually, you need to send the username and password to a "sign in" route which will then return a token. Then you pass the token with other requests to get authorization. Since I don't know any details about your server and API, I can't provide any more details to help you out.
I would really appreciate some help here. I am trying to use the Spotify API to add albums to a users library. I have been struggling with a Malformed Json Payload, and am completely out of ideas.
Here is a simplified version of what I am currently sitting on
url = 'https://api.spotify.com/v1/me/albums'
payload = {'body': ['01kTgTBiZkCFY3ZH2hBH6u', '4sz6Fn4BYORRLIc1AvQwQx']}
headers = {'Authorization':'Bearer {}'.format(access_token), 'Content-Type':'application/json',}
response = requests.put(url,headers=headers, data=payload)
print(response.json())
The error I am receiving is in the json response:
{'error': {'status': 400, 'message': 'Malformed json payload'}}
I have tried changing requests.put as per below, but all attempts are returning the same error
response = requests.put(url,headers=headers, json=payload)
response = requests.put(url,headers=headers, data=json.dumps(payload))
response = requests.put(url,headers=headers, json=json.dumps(payload))
07bYtmE3bPsLB6ZbmmFi8d: This spotify id is for the album, Dancefloor Hits #1. I checked my spotify acct and there it was in my Albums on my acct. Below is my code to run that.
import requests
url = "https://api.spotify.com/v1/me/albums"
payload = {"ids": "27cZdqrQiKt3IT00338dws"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % (access_token) # paste your access token in here
}
''' you can use the same syntax as above but the key was that your ID of album had to be a **parameter** not ***data***.
To do that you use the params kwarg'''
response = requests.request("PUT", url, headers=headers, params = payload)
print(response.status_code) # should print out 200 when you run the code
# shows whether status was valid
Everyone!
I'm trying to request from an API in python like so:
headers = {"Content-Type": "application/json", "user-key": self.api_key}
params = {self.filter_fields: '*', self.filter_date: self.date_millis, self.limit: '2'}
request = requests.get(self.api_endpoint, headers=headers, params=params)
I double checked and see no problem with my filters nor api key. The problem is that when the I print the request content "print(request.json())" I get this following error:
{'Err': {'status': 400, 'message': "Invalid content encoding please change 'Content-Type' header."}}
The code performs a GET request. It specifies that the content type is JSON, however, there is no JSON content being passed in the body of the request.
Try omitting the content-type header.
Another possibility is to pass the parameters using the json parameter. The content-type does not need to be set in the headers, requests will send it automatically:
headers = {"user-key": self.api_key}
params = {self.filter_fields: '*', self.filter_date: self.date_millis, self.limit: '2'}
response = requests.get(self.api_endpoint, headers=headers, json=params)
I tried to send file with some headers like:
files = {'file': (file, open(file, 'rb'), {'Content-type': 'multipart/form-data; boundary=---BOUNDARY', 'Authorization' : 'Basic ' + api_key})}
r = requests.post(base_url, files=files)
Server returned 401 error that means absent header Authorization. But I sent it
For Basic Authentication you can follow the requests docs. It's visible on the very first line of code in the example on that page.
Use the auth keyword argument to supply a 2-tuple of username and password:
response = requests.post(base_url, files=files, auth=('username', 'password'))
Edit:
If you want to send actual headers, rather than things like Basic Auth, you can do that with the headers keyword argument. This allows you to give a dict of headers you would like to send. For example:
headers = {'Content-Type': 'application/json'}\
response = requests.post(url, data=data, headers=headers)
The auth argument, should be a simplification of the above because Basic Auth is so common, but don't quote me on that one.
You can follow this example to take it from the official documentation I think you should try it first in postman, with the json then and do it from python.
This information is taken from the official documentation
python
I am relatively new to python and enjoying every day I program in it. I have been looking around for a possible solution to figure out how to post an image in a multipart-form, binary format, with a form tag. The API I am trying to call is expecting a binary image in a form.
The request payload sample I have is:
----WebkitFormBoundaryM817iTBsSwXz0iv8
Content-Disposition: form-data, name="image"; filename="123BMW.jpg"
Content-Type: image/jpeg
----WebkitFormBoundaryM817iTBsXwxz0iv8
I have tried several ideas based on some basic requests examples.
Any ideas, thoughts or pointers on where to start looking for such a solution?
def Post_Image(urlPath, filePath, fileName):
url = urlPath headers = {'content-type': 'multipart/form-data'}
files = {'file':(fileName, open(filePath,'rb'))}
payload = {"Content-Disposition": "form-data", "name":fileName}
payload = urllib.urlencode(payload)
resp = requests.post(url, data=payload, headers=headers, files= files)
The problem is you're setting both the data and files parameters, this part of the code sample here:
payload = urllib.urlencode(payload)
resp = requests.post(url, data=payload, headers=headers, files= files)
If both are present, and data value is a string, only it will be in the request. Drop it, and the files will be present.