I am making a request to an API, I'm using basic authorization, yet for some reason the API is unable to decode the authorization string
Here is the code I'm using:
import base64,requests
from base64 import b64encode
url = 'api.sample/test'
APIuser = b'generic_user'
APIpass = b'generic_pass'
myobj = {"data1_field":"data1"}
data_string = APIuser + b":" + APIpass
data_bytes = b64encode(data_string).decode('ascii')
head = {'Content-Type':'application/json', 'Accept':'*/*','Authorization':'Basic ' + data_bytes}
x = requests.post(url, headers=head,
data = myobj)
print(x.text)
this is the error I'm getting:
{
"error": {
"detail": "Cannot decode: java.io.StringReader#45fab9",
"message": "Exception while reading request"
},
"status": "failure"
}
Any ideas of what am I doing wrong?
B64 is read as a byte data on python, so the string will be represented as b'x', so the way of doing it is sending the encryption type on the response, also i was using ascii encoding, and the required one is utf8, important not to mistake it with utf-8 (apparently not the same for the compiler)
url = "api.sample/test"
payload = "{\"Data1\": \"Data1_field\"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic get the string'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
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 have this command
curl -X POST --data-urlencode "payload={\"channel\": \"#test\", \"username\": \"kuhkuh\", \"text\": \"This is posted to #test\", \"icon_emoji\": \":ghost:\"}" https://hooks.slack.com/services/123/123/123
im trying to create it using python so i can use it on my project
import requests
import json
class SlackWrapper:
def __init__(self):
pass
#classmethod
def post_message_to_slack(self, err):
url = 'https://hooks.slack.com/services/123/123/123'
payload = {
'channel' : '#test',
'username' : 'kuhkuh',
'message' : err,
'icon_emoji' : ':ghosts:'
}
try:
alert = requests.post(url, data=payload, headers={'Content-Type': 'application/json'})
print(alert.status_code, ' - ', alert.text, ' - ', json.dumps(payload))
except Exception as e:
print(e)
SlackWrapper.post_message_to_slack("testing error message requests")
the problem is, i keep geting this error
<Response [400]>
where did i went wrong?
Error 400 means "Bad Request", so your payload is wrong.
If your payload is already a dict there is no need to json.dumps it in the json parameter of the post request. Also requests is smart enough to infer the Content-Type, so no need to explicitly set this Header.
#classmethod
def post_message_to_slack(self, err):
url = 'https://hooks.slack.com/services/123/123/123'
# changed the payload
payload = {
"channel": "#test",
"username": "kuhkuh",
"text": "This is posted to #test",
"icon_emoji": ":ghost:"
}
try:
# changed the parameters for posting
alert = requests.post(url, json=payload)
print(alert.status_code, ' - ', alert.text, ' - ', json.dumps(payload))
except Exception as e:
print(e)
You can paste the curl code to postman then get the python code and use that.
For your code the equivalent python code :
import requests
url = "https://hooks.slack.com/services/123/123/123"
payload = 'payload=%7B%22channel%22%3A%20%22%23test%22%2C%20%22username%22%3A%20%22kuhkuh%22%2C%20%22text%22%3A%20%22This%20is%20posted%20to%20%23test%22%2C%20%22icon_emoji%22%3A%20%22%3Aghost%3A%22%7D'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
You are trying to send the data to the server as a dictionary.
Instead try sending it as a json data using requests POST json attribute
payload = {
"channel" = '#test',
"username" = 'kuhkuh',
"message" = err,
"icon_emoji" = ':ghosts:'
}
alert = requests.post(url, json = payload)
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})