I'm using Python's request package with the following code:
APIKEY = "XXX"
url = 'https://services.kommunicate.io/rest/ws/message/v2/send HTTP/1.1'
myobj = {
'groupId': "xxx",
'message':'Hello',
"fromUserName":'yyy'
}
headers = {
'Api-Key':APIKEY,
}
response = requests.post(url, data = myobj,headers=headers)
And is giving me the following error:
'{"status":"error","errorResponse":[{"errorCode":"AL-MA-01","description":"method not allowed","displayMessage":"Request method \\u0027POST\\u0027 not supported"}],"generatedAt":1591385905404}'
What am I doing wrong?
There are few issues with the code.
1. HTTP/1.1 is not part of the URL.
2. In requests package, in order to pass a JSON to server, there are multiple ways to do.
a. Use json parameter provided in requests.post method for sending JSON data to the server, something like below code:
import requests
APIKEY = "XXX"
url = 'https://services.kommunicate.io/rest/ws/message/v2/send'
myobj = {
'groupId': "xxx",
'message': 'Hello',
"fromUserName": 'yyy'
}
headers = {'Api-Key': APIKEY}
response = requests.post(url, json=myobj, headers=headers)
b. In Headers add "Content-Type": "application/json" and then first dump json data to string and then send it to server.
import requests
import json
APIKEY = "XXX"
url = 'https://services.kommunicate.io/rest/ws/message/v2/send'
myobj = {
'groupId': "xxx",
'message': 'Hello',
"fromUserName": 'yyy'
}
headers = {
'Api-Key': APIKEY,
"Content-Type": "application/json"
}
myobj = json.dumps(myobj)
response = requests.post(url, data=myobj, headers=headers)
Also, Do check Difference between data and json parameters in python requests package
Related
This is a python script to make a post call with respective header and body, but I am getting error Full authentication is required to access this resource
import requests
from requests.auth import HTTPBasicAuth
url = 'https://localhost:8000/bucket/items'
body = {
"serialNumbers": [
"AASD-ASD"
]
}
bearer_token = "07eb4900-016f-4523-a9b7-e5d6a87a7f8e"
jwt_token = "jhbasdfiunnX.faf-"
headers = {'content-type': 'application/json',
"authentication":"bearer "+ '07eb4900-a9b7-e5d6a87a7f8e',
"cookie":"jwt="+jwt_token}
headers = {"Cookie":"JWT="+jwt_token, "Authentication":"Bearer "+bearer_token, "Content-Type": "application/json" }
response = requests.post(url, body, auth=HTTPBasicAuth("abcd", "password"),headers=headers).json()
print(response)
I am trying to debug a POST request which returns 400 using requests library.
The request is of type:
POST https://somesite.com/path?key=value
{
"some": "payload"
}
So it has both query parameters and body.
Inspecting the response.request object I can see that the body property is null so the problem could be I am passing the arguments in the wrong way, but I couldn't figure out where the issue is.
import requests
import json
session = requests.Session()
response = session.request(
url='https://somesite.com/path?key=value',
method='POST',
headers={
'Content-Type': 'application/json'
},
json={
'some': 'payload',
}
)
print(response.status_code) # 400
print(response.request.body) # null
Following this discussion, I've also tried to extract the query parameters from the url and pass them using params in the request, but still no luck (400 and response.request.body=null):
import requests
import json
session = requests.Session()
response = session.request(
url='https://somesite.com/path',
method='POST',
headers={
'Content-Type': 'application/json'
},
params={'key': 'value'},
json={
'some': 'payload',
}
)
print(response.status_code) # 400
print(response.request.body) # null
What am I doing wrong?
I'm having issues receiving the bearer token using Python for the Microsoft Graph API. Here is what I have so far:
import requests
import json
headers = {
'Content-Type': 'x-www-form-urlencoded',
'Authorization': 'Basic'
}
data = {
"grant_type": "client_credentials",
"client_id" :"<client_id>",
"client_secret": "<client_secret>",
"resource": "https://graph.microsoft.com"
}
r = requests.post('<token_address>', headers=headers, data=data)
print(r.text)
I have it worked in Postman, through x-www-form-urlencoded, but can't seem to get it working in Python. It returns The request body must contain the following parameter: 'grant_type'. I realize the problem probably has to do with needed the data converted, but I am not sure where to start.
You're sending some invalid headers in your request:
The Content-Type should be application/x-www-form-urlencoded not x-www-form-urlencoded.
You shouldn't be sending an Authorization header at all.
Technically, since requests.post sends data as form encoded by default, you can safely remove your headers from the request:
payload = {
'grant_type': 'client_credentials',
'client_id': '<client_id>',
'client_secret': '<client_secret>',
'resource': 'https://graph.microsoft.com',
}
r = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=payload)
print(r.text)
I believe that OAuth expects the body to be URL-encoded, like this:
data = "grant_type=client_credentials"
+ "&client_id=<client_id>"
+ "&client_secret=<client_secret>"
+ "&resource=https://graph.microsoft.com"
Looking to connect to the Gooddata API and export a report via the API in python. The documentation is a bit confusing to follow.
I've defined a login to my instance of gooddata:
from urllib2 import Request, urlopen
import json
import requests
def login_gooddata(my_email, my_password):
url = 'https://secure.gooddata.com/gdc/account/login'
values = {
"postUserLogin": {
"login": my_email,
"password": my_password,
"remember": 0,
"verify_level": 0
}
}
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
encoded_values = json.dumps(values)
#request = Request(url, data=encoded_values, headers=headers)
r = requests.post(url, data=encoded_values)
return r
That successfully logs me in, returning a 200 response.
Given the documentation from the gooddata website on connecting to the API, I'm trying to export a raw project file.
I set the project and object ids:
project_id = 'asibfakuyebkbhdbfaisdf'
object_id = '87234760'
values = {
"report_req": {
"reportDefinition": "/gdc/md/"+ project_id + "/obj/" + object_id
}
}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
url = 'https://secure.gooddata.com/gdc/app/projects/' + project_id + '/execute/raw/'
r = requests.post(url, data=json.dumps(values), headers=headers)
request = Request(url, data=json.dumps(values), headers=headers)
response_body = urlopen(requests).read()
print response_body
I played around with using r = requests.post(url, data=encoded_values and request = Request(url, data=encoded_values, headers=headers). Still receiving an error. I'm not really sure how to tackle next steps.
Following directions as stated in documentation for connecting to the API:
You need to perform all HTTP requests from a single "session" that remembers cookies from the login: perform s = requests.Session() once, then use s.post instead of requests.post.
See https://stackoverflow.com/a/31571805/3407728 for more.
I'm trying to convert the cURL to Python request but doesn't work.
cURL: curl -kv -H 'Content-Type: application/json' 'https://IP-address/api/v1/login' -d '{"username":"api", "password":"APIPassword"}'
My Python requests code:
import requests
url = "https://IP-address/api/v1/login"
payload = "'{\"username\":\"api\", \"password\":\"APIPassword\"}'"
headers = {
'Content-Type': "application/json",
'cache-control': "no-cache",
}
response = requests.request("GET", url, headers=headers, data=payload, verify=False)
print(response.text)
Which doesn't work and gives me 400 bad requests error.
I tried converting using the https://curl.trillworks.com/
which gives me the following code which doesn't work either.
import requests
url = 'https://IP-address/api/v1/login'
headers = {
'Content-Type': 'application/json',
}
data = '{"username":"api", "password":"APIPassword"}'
output = requests.get(url, data=data, verify=False)
print (output)
Can anyone please help me identify the issue here.
Edit: I have edited 2nd script to produce output: Which gives 500 Error
Use the json parameter in requests.post for json data. It also takes care of the headers.
data = {"username":"api", "password":"APIPassword"}
response = requests.post(url, json=data, verify=False)
Another way to make sure you're sending valid JSON in your payload would be to use the json python library to format your payload via json.dumps(), which returns a string representing a json object from an object. This was especially useful to me when I needed to send a nested json object in my payload.
import json
import requests
url = 'https://sample-url.com'
headers = { 'Content-Type': 'application/json', 'Authorization': f'{auth_key}'}
payload = { "key": "value",
"key": ["v1", "v2"],
"key": {
"k": "v"
}
...
}
r = requests.post(url, headers=headers, data=json.dumps(payload))