POSTMAN i have tried everything to duplicate a POSTMAN POST that is working using Python and i have been unsuccessful. I receive a 500 back and when i print the request I dont see anything wrong. Any suggestions?
```
filename1="untitled.png"
filename="untitled.png"
location = "C:\\myfiles\\"
#files = {"file":(filename1,open(location+'/'+filename,"rb"),'application-type')}
#files = {"file":(filename1,open(location+'/'+filename,"rb"))}
#files = {"file":(filename1, open(location+'/'+filename,'rb'),'application-type')}
files = {'file': (filename1, open(location+'/'+filename,'rb'))}
payload = {'': {
"DateIssued": "2020-02-22T14:35:40.760026-08:00",
"Category":None,
"Title":"Report",
"Title2":"MyReports"
}}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'PublishService-Api-Key': 'myAPIKey'
}
req = requests.request('POST',"http://myurl.com/PublishService/api/docs/", headers=headers, data=payload, files=files)
print(req)
```
Just remove the Content-Type from header.
headers = {
'PublishService-Api-Key': 'myAPIKey'
}
Explanation here --> How to send a "multipart/form-data" with requests in python?
Related
Trying to get Work Items for an Azure DevOps Project.
import requests
import base64
from azure.devops.connection import Connection
from azure.devops.v5_1.work_item_tracking.models import Wiql
from msrest.authentication import BasicAuthentication
organization = "https://dev.azure.com/dev"
pat = 'ey3nbq'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic '+authorization
}
payload = {
"query": "SELECT [System.Id] FROM workitemLinks WHERE ([Source].[System.WorkItemType] = 'Task') AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Reverse') AND ([Target].[System.WorkItemType] = 'User Story') MODE (DoesNotContain)"
}
response = requests.post(url="https://dev.azure.com/dev/Agile_Board/_apis/wit/wiql?api-version=5.1", headers=headers, data=payload)
print(response.text)
Gives response 400
Have tried many things, been struggling a bit with this. Any help is much appreciated. How to get project's work items without using their ID . Does the request need to be changed in some way?
Update your post to (json=payload):
response = requests.post(url="https://dev.azure.com/YOUR_ORG/Agile_Board/_apis/wit/wiql?api-version=5.1", headers=headers, json=payload)
or use something like this:
payload_str = "{\"query\": \"SELECT [System.Id] FROM workitemLinks WHERE ([Source].[System.WorkItemType] = 'Task') AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Reverse') AND ([Target].[System.WorkItemType] = 'User Story') MODE (DoesNotContain)\"}"
response = requests.post(url="https://dev.azure.com/YOUR_ORG/Agile_Board/_apis/wit/wiql?api-version=5.1", headers=headers, data=payload_str)
Check this question: How to POST JSON data with Python Requests?
I am trying to upload an image using POST request. From Postman, it is giving success but when I try same code from python, I am getting an error (payload validation failed). Following is my code in python:
import requests
url = "http://10....."
payload = {}
files=[('pdf_file',('passport.jpg', open('/D:/passport.jpg','rb'), 'image/jpeg'))]
headers = {
'accept':'application/json',
'Content-Type':'multipart/form-data',
'Authorization':'<token_here>',
}
response = requests.request("POST", url, headers = headers, data = payload, files = files)
print(response.text)
While invoking request from postman, headers are same as above code. Select form-data in body section and upload image for key "pdf_file".
Is there any difference in both approaches?
You should omit content type from headers
headers = {
'accept':'application/json',
'Authorization':'<token_here>'
}
I am getting the error message "Bad Gateway
The proxy server received an invalid
response from an upstream server" with the following code:
import requests
url = "https://apis.company.com/v3/media"
attachments = 'media': ('x.mp3', open('x.mp3', 'r'))}
headers = {'content-type': "multipart/form-data",'cache-control': "no-cache"
'Authorization':"Bearer zzz" }
response = requests.post(url, files=attachments, headers = headers)
print response.text
I'm following the example in the requests Quickstart documentation, where it says "You can also pass a list of tuples to the data argument": http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
What is causing this error and how can I fix it?
The main problem was that I set the content-type in the header. This code works:
import requests
url = 'https://apis.company.com/v3/media'
token = 'token-goes-here'
headers = { 'Authorization' : 'Bearer ' + token }
filename = 'x.mp3'
with open(filename, 'rb') as media_file:
attachments = {
'media': (filename, media_file, 'application/octet-stream')
}
response = requests.post(url, files = attachments, headers = headers)
print response.text
I'm trying to post JSON to an URL but the response seems to be wrong.
url = "www.example123.com/someurl"
mypayload = { //JSON PAYLOAD }
response = request.post(url, post = payload, auth = ("USERNAME", "PASSWORD"))
print(response.content)
But it does not seem to work. What is wrong with the code?
You need the appropriate header for the specifying its JSON data.
Try :
headers_JSON = {'content-type': 'application/json'}
response = request.post(url, JSON = mypayload, headers = headers_JSON, auth = ("USERNAME", "PASSWORD"))
Also note, instead of post = payload, use JSON = payload.
If that doesn't work use:
post = JSON.dumps(payload)
A quick look at the documentation will help : http://docs.python-requests.org/en/master/user/quickstart/
var retval = jQuery.ajax({
type:'post',
url: url,
contentType: 'application/json',
data: JSON.stringify(data)
});
You can see in above jquery ajax we are setting content Type to "application/json"
You can see in your request payload what it is. It all depends upon what your server API is expecting means Content Type.
I'm trying POST a check-in request in Google Places API. The way they described it, I have to request this -
POST https://maps.googleapis.com/maps/api/place/check-in/json?sensor=true_or_false&key=AddYourOwnKeyHere HTTP/1.1
Host: maps.googleapis.com
{
"reference": "place_reference"
}
My Current code looks like this -
def checkin(self, reference="", sensor="true"):
"""
"""
base_url = "https://maps.googleapis.com/maps/api/place/check-in/json"
params = urllib.urlencode(
{
'key': self.API_KEY,
'sensor': sensor,
}
)
post_url = base_url + "?" + params
headers = { 'Host': "maps.googleapis.com" }
data = urllib.urlencode({ 'reference': reference })
req = Request(post_url, data, headers)
response = urllib2.urlopen(req)
resp = response.read()
But I keep getting the error -
urllib2.HTTPError: HTTP Error 400: Bad Request
What am I doing wrong?
Your problem is that the API is expecting JSON when you are sending it the literal reference: xyz
You need to send it the JSON representation.
Try:
data = json.dumps({'reference': reference})