Moodle Create User API Invalid Parameter Exception - python

I am trying to register a user via API using Python Request.
Here is my code
import requests
url = "www.website.com/webservice/rest/server.php?createpassword=1&username=thisissifumwike&auth=manual&password=Tester#2023.&firstname=Domain&lastname=Tester&email=hello#gmail.com&maildisplay=sifugmail&city=Daressalaam&country=Tanzania&timezone=99&description=I am a good tester&firstnamephonetic=Sifu&lastnamephonetic=Domain&middlename=Tester&alternatename=Tunety&interests=books, codes, forex&idnumber=FMM001&institution=FMM&department=Traders&phone1=0611222333&phone2=0611333222&address=Daressalaam&lang=en&calendartype=gregorian&theme=default&mailformat=1&customfields=&wstoken=token&wsfunction=core_user_create_users&moodlewsrestformat=json"
payload={}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
However upon sending that request I get this response
{
"exception": "invalid_parameter_exception",
"errorcode": "invalidparameter",
"message": "Invalid parameter value detected"
}

Related

Why twitter api request get Expecting value: line 1 column 1 (char 0)?

I got the below error when using a Twitter API request to change PFP:
'Expecting value: line 1 column 1 (char 0)'
And this for the Code
picture = [f for f in os.listdir("pfp/") if isfile(join("pfp/", f))]
random_picture = random.choice(picture)
with open(f'pfp/{random_picture}', "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
cookies = {
'auth_token': x
}
headers = {'Content-Type': 'multipart/form-data'}
params = f"image=data:image/png;base64,{(encoded_string.decode('utf-8'))}"
response = requests.post('https://api.twitter.com/1.1/account/update_profile_image.json',
cookies=cookies, params=params, headers=headers, proxies=proxies)
is the my code wrong ?
Any help is appreciated.
Thing which you need to provide:
method: POST
url: https://api.twitter.com/1.1/account/update_profile_image.json
parameter as encoded url-safe Base64 (so for example + should be changed to %20) for example: iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAACXBIWXMAABwgAAAcIAHND5ueAAAAJklEQVQImWMQibsx73%20NSNyNGyIiDBAWhGSAs%20b9r2G4ISIC5wMAg%20IY55xszl4AAAAASUVORK5CYII%3D
header to authorise user: auth_token: 1610678221XXX-ab5sYYYYY
headers to authorise application (for OAuth 1.0 HMAC-SHA1)
Authorization headers - RFC 5849: The OAuth 1.0 Protocol
How to build it, check here:
https://www.rfc-editor.org/rfc/rfc5849#section-3.5.1
or here:
https://stackoverflow.com/a/67668940/5529263
For python you can use Requests-OAuthlib library
Example of code:
import requests
image = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAACXBIWXMAABwgAAAcIAHND5ueAAAAJklEQVQImWMQibsx73%20NSNyNGyIiDBAWhGSAs%20b9r2G4ISIC5wMAg%20IY55xszl4AAAAASUVORK5CYII%3D"
url = "https://api.twitter.com/1.1/account/update_profile_image.json?image=" + image
headers = {
'auth_token': '12341234512345234512345-abcedfghijklm',
'Authorization': 'OAuth '
'oauth_consumer_key="ABCD1234ABCD1234ABCD1234",'
'oauth_signature_method="HMAC-SHA1",'
'oauth_timestamp="1234567890",'
'oauth_nonce="MNOPRST0987MN",'
'oauth_version="1.0",'
'oauth_signature="ABCDEFGHIJ1234ABCDEFGHIJ"',
}
response = requests.request("POST", url, headers=headers, data={})
print(response.text)
After sending correct request you can receive response with code 403
{
"errors": [
{
"message": "You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve",
"code": 453
}
]
}
so it means you need to apply for Elevated access, here you have more information:
https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-level

Send image in request from python

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>'
}

Python API Call authorization returns 401 for over the retrieval failure of JSESSIONID/Cookie/ClientID by request library

I have simulated successfully API calls with my postman client.
Postman client automatically populates the required JSESSIONID, COOKIE, and CLIENT ID.
However, when I try to realize the same with python I get 401. It looks like the session variable of the request API does not hold the required information
I would like to replicate the entire step below with both Postman generated python script and my script
Postman script
In the first POST call, I use my secretKey to request the secret
import requests
url = "https://url.com/v1/session/auth/token?X-Requested-By=Maddy&Content-Type=application/x-www-form-urlencoded"
payload="secret_key=zxcvfc-103f-950d-856d-cxvfdgh&username=myuser001&access_level=FULL"
headers = {
'X-Requested-By': 'Maddy', #This is my header
'Content-Type': 'application/x-www-form-urlencoded', #My header
'Cookie': 'route=e7esaafb42ce234234242347482341f; clientId= zxcvfc-103f-950d-856d-cxvfdg; JSESSIONID=e34cc53d-e99c-4296-a4fe-0d70a246bd11' #Postman generated
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I get a secret JHNXZasdasdasdasjdakdasdjdalsdjasdladasdlalsdjajsdjaskdjaksjdaskjdjaskdljasj very long
then the second GET call is done with the secret I have received.
import requests
url = "https://url.com/callosum/v1/session/login/token?username=myuser001&auth_token=JHNXZasdasdasdasjdakdasdjdalsdjasdladasdlalsdjajsdjaskdjaksjdaskjdjaskdljasj&redirect_url=https://url.com/callosum/v1/tspublic/v1/user/list"
payload={}
headers = {
'Cookie': 'route=e78as0dad9009q029420349249f; clientId=s0255-6598-5103-dec3-defererer090; JSESSIONID=dfgas8484-659595656-6526-5626-7589898ads'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
#The response contains JSON output with a list of users
Not the above header junk that contains id and session and cookie is generated by the postman
Now this is how my Python script looks like
url = "https://url.com/callosum/v1/session/auth/token?X-Requested-By=Maddy&Content-Type=application/x-www-form-urlencoded"
payload="secret_key=zxcvfc-103f-950d-856d-cxvfdgh&username=myuser001&access_level=FULL"
headers = {
'X-Requested-By': 'Maddy', #These one is mine
'Content-Type': 'application/x-www-form-urlencoded' #these one is mine
}
with requests.session() as s:
secret = s.post(url, data=payload, headers=headers,verify=False).text
#secret contain the lengthy secret for the get call stored in the variable secret
payload1 = {}
#The url2 contains login url and redirect url that contains the user API for get method
url2 = "https://url.com/callosum/v1/session/login/token?username=myuser001&auth_token={}&redirect_url=https://url.com/callosum/v1/tspublic/v1/user/list".format(secret)
r = s.get(url2,data=payload1,verify =False)
#Also tried without payload and with and without header results are the same
print(r.cookies)
print(r.text) #401 unauthroized
I get the secret but not the data. Do let me know if there is something that needs to be added.
Best Regards,
Gabby

Rest API with oauth2 work just in browser, error in python

i can access a API by browser requesting URL?access_token=jdjdfjhdjkdhf for example, and open a json in browser with datas, so 200 OK
The api is Oauth2.0
When i try open this same API in python, i'm receveing a 401 error, i check the readers but can't access, code below
import requests
import json
url = 'https://www.myRUL/web_api/auth' #url de obtenção token
consumer_key = 'MYCONSUMERKEY'
consumer_secret = 'MYSECRET'
code = 'MYCODE'
payload = {'consumer_key' : consumer_key,'consumer_secret' : consumer_secret,'code' : code}
response = requests.post(url, json=payload)
response = response.json()
print(response)
At this point I can receive a access_token into a json in python, with a 200OK code, so I try access data with my ne access_token
Something like that, just a example json with no real datas:
HTTP/1.1 201 OK
{
code: 201,
message: "Created tokens",
access_token: "abc96fb7b1defd2496b9a9d81071fa12319b12306465e057d0ebca9bd9ab19",
refresh_token: "bbc96fb7b1defd2496b9a9d81071fa12319b12306465e057d0ebca9bd9ab19",
date_expiration_access_token: "2016-08-12 14:35:14",
date_expiration_refresh_token: "2016-09-11 11:35:14",
date_activated: "2016-08-12 11:35:14",
store_id: "123123"
}
And than, finally when i try acceses the api with my access_token
url_orders = 'myURL/web_api/orders' #url de consulta
headers = {"Accept": "application/json"}
pay = {'access_token': response['access_token']}
print(requests.get(url_orders, json=pay))
So i receive a error 401
What I'm doing wrong
Thank you

Starting a conversation with a chat bot hosted on Microsoft Azure through HTTP request in Python

A Microsoft tutorial shows that in order to set up a conversation with a bot I should issue the following HTTP request:
POST https://directline.botframework.com/api/conversations
Authorization: Bearer SECRET_OR_TOKEN
My question is if I can achieve this with the following Python code:
import requests
r = requests.post('https://directline.botframework.com/api/conversations',
params = {'Authorization':'Bearer ftmhNAqZ2tw.cwA.qIA.Xz2ZWfYJzxd8vJjcK9VmINWNLxlvKiM5jC8F_cbaf0s'})
If I print the response with print(r.content) it says:
{ "error": {
"code": "BadArgument",
"message": "Missing token or secret" } }
HTTP requests have three areas where content can be sent:
URL parameters
Body
Headers
To set these in python's requests package the following can be used (POST method assumed, but all are the same):
URL Parameters:
requests.post('https://myurl.com', params = {'MyParam':'MyValue'})
# equivilient to http://myurl.com?MyParam=MyValue
Body:
requests.post('https://myurl.com', data={"key":"value"})
# or if sending json data
requests.post('https://myurl.com', data=json.dumps(myData))
Headers:
requests.post('https://myurl.com', headers={"headername":"value"})
In your specific case, while the API is not well documented - we can assume they expect the "Authorization" data to be sent in a header, as this is standard. In this case, you need to assign headers as follows:
requests.post('https://directline.botframework.com/api/conversations', headers={'Authorization':'Bearer ftmhNAqZ2tw.cwA.qIA.Xz2ZWfYJzxd8vJjcK9VmINWNLxlvKiM5jC8F_cbaf0s'})
The bearer token needs to be sent as a header, not as a payload or query parameter.
You need to use the headers argument:
auth = {'Authorization': 'Bearer xxxYourBearerTokenHerexxx'}
r = requests.post('https://directline.botframework.com/api/conversations', headers=auth)
print(r) # <Response [200]>

Categories

Resources