How can i capture result of requests.POST in Python? - python

I am quite new to Python and was trying to simulate the result captured when testing API POST requests in Postman. I am basically trying to capture the token generated using the Post method.
I have the following details in Postman which gives me the token details.
Authorization Tab: Type: Basic Auth, Username, Password
Headers Tab: Content-Type: application/x-www-form-urlencoded, Authorization: #This is Auto-Filled
Body Tab: raw: grant_type=client_credentials&scope=read_snfa_unifiedgateway
Now when i run with above details in Postman, it gives me access token in the result but when i use the same details using the following Python Code, i get only <Response [200]> as result for response variable.
import requests
url = 'https://appurl.com/oauth/ls/connect/token'
body = 'grant_type=client_credentials&scope=read_snfa_unifiedgateway'
response = requests.post(
url,
body,
auth=HTTPBasicAuth('my_username', 'my_password'), headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
How can i change the above Python code in such a way that i could get the result in the format i get in Postman as following and then i could use the access_token value in next operation for another POST Method?
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbsdfsdfsdfsdfcsdcsdvarglkwelkrmgmasdmnfjtugnasmdfisdfmmmmpeirhg_-e60s72zgV8Gn2hUiWwlelNQhJongUW6fxwD42c1N5u4R2JJdrj5V_bIwnvY_C_l5wHlIFSQRE1E-5KzP7WG9XjmV9oXRXXGjNhwRqEocGdiEMjcibyiYQNZmG2h-GbsTKvCc21hRNhyRF_y4mdwVUytAXT68TuwZxsTbjUzEvPdwd2JZaFnD9Elo7akSk2ROnRMxN70fsoLzEK71kbzoYkti1jX_V8i_s6K0wmLma-x4nc2kW5mpFM0R9NPqH-kGf-4ZUKim03frifpsGl6Nqo-eN5oZ-b6YgK56mSjxpxQ",
"expires_in": 3600,
"token_type": "Bearer"
}

Use response.json() to get result in dict format. You can use
access_token = response.json()['access_token']

Related

How get bearer token with requests from python

I'm trying to replicate a login to a page with python and the requests module but I need a token bearer.
This site doesn't require a login password connection but just an event code (wooclap.com)
I cannot find when the token is recovered by looking at header and json responses.
If you can help me
Thanks
once you put in a event code check the network tab on you're chrome console there should be a request wich returns the token. either in the reponse header or the json,
I'd recommend finding it using DevTools in your browser (F12).
In network you can see the login request mainly under headers and response. I've used this to implemented it below in python for you.
import requests
# Set the URL of the login page
url = "https://app.wooclap.com/api/auth/local/login"
# Set the login credentials
data = {"username": "< !!enter username here!! >", "password": "< !!enter password here!! >"}
# Send the login request and store the response
response = requests.post(url, data=data)
# Get the JSON response body
json_response = response.json()
# Get the AWT token from the JSON response
awt_token = json_response.get("token")
# Set the URL of the resource you want to access
url = "https://app.wooclap.com/public/events"
# Set the authorization header of your request, using the Bearer scheme
headers = {"Authorization": f"Bearer {awt_token}"}
# Send the request and store the response
response = requests.get(url, headers=headers)
print(response.text)
To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header

How to take take access tokens from oauth2

I'm having problems on taking the access token from the oauth2 platform with python.
Currently, that's what I'm using on my post request:
def token(self):
client_id=ID_DO_CLIENTE
client_secret=SECRET_TOKEN
grant_type='client_credentials'
response = requests.post("https://oauth2.googleapis.com/token",
auth=(client_id, client_secret),
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
print(response.text)
This specific code is returning the following error:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
But I don't think the problem is the grant_type, since I've tried everything I've found online to solve this.
Anyway, if there's any info missing, please let me know. Please help !
A valid request will also need these headers in order to send data in the correct format - I suspect JSON is sent by default, resulting in a malformed request:
Content-Type: application/x-www-form-url-encoded
Authorization: Basic [base 64 encoded client id and secret]
TECHNIQUES
Aim to use the curl tool to get the token first, to ensure the setup is right - as in this article.
Also aim to trace the request via an HTTP proxy tool to ensure that the wire message is being sent correctly.
These techniques will make you more productive when working with OAuth.
CODE
I had a search and this answer seems to use the correct code, though you may be able to send the Authorization header like this:
auth=HTTPBasicAuth('user', 'pass')
This is a sample code for reference:
data = {'grant_type': 'client_credentials'}
requests.post(token_url,
data=data,
auth=(client_id, client_secret))
In the provided sample code, the data part is being sent incorrectly viz:
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret}
I think it should be this:
data={'grant_type':grant_type}
Adding the sample code which I am testing to verify the token generation logic:
client_id = '<value>'
client_secret = '<value>'
# This is optional
scope = '<uri>'
#Token generation step
#If scope is not defined above then remove it from this call
data = {'grant_type': 'client_credentials','scope': scope}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print (access_token_response.headers)
print (access_token_response.text)
tokens = json.loads(access_token_response.text)
print ("access token: " + tokens['access_token'])

Python API Post Request URL Returning Error

I'm trying to use this service, Buffer, to publish a post on Facebook through API.
Here's my code:
params = {
'profile_ids': ids,
'text': "text",
'access_token': access_token
}
r = requests.post('https://api.bufferapp.com/1/updates/create.json', params=params)
print r.json()
print(r.url)
But when run I it, it prints out this message:
{"success":false,"message":"Please select at least one account to post from.","code":1004}
This is the URL used to make the request:
https://api.bufferapp.com/1/updates/create.json?access_token=ACCESS_TOKEN&text=TEXT&profile_ids=LIST_WITH_PROFILE_IDS
I made sure the id is correct and I got it both manually and through API still, I get the same message.
The only required parameter is the profile_ids which should be an array. Here's the documentation on their website about publishing posts("updates"): https://buffer.com/developers/api/updates
What am I doing wrong here?
It seems that the API expects the data in the post request payload, not as url parameters.
Use data, not params.
r = requests.post('https://api.bufferapp.com/1/updates/create.json', data=params)
# -------------------------------------------------------------------^^^^ here

how to save authentication cookie while doing POST login into the server

I am trying to login into the server via post with my python script, but it is not working although when i am doing the same POST via postman it is working fine. I believe my python script is not saving the authentication cookie information or may be i have to add some more fields in my payload. I am at very very beginner level of programming so please guide me how i can save that authentication cookie which i can further use in my next GET, POST requests.
When i run this POST request via postman. I simply give username and password in the body and i got the following successful response
{
"ErrorCode": 0,
"Data": {
"role": "admin",
"_id": "7c9e7mdf4d249212282480zb",
"name": "test5"
}
}
but when I run below mentioned Python script, I am getting
<!DOCTYPE HTML PUBLIC"-//IETF//DTD HTML 2.0//EN">
500 Internal Server error
Please find below mentioned my python script
import requests
url = "http://172.125.169.21/api/user/login"
payload = "{\"name\": \"test5\", \"password\": \"Hello123\"}"
response = requests.request("POST", url, data=payload)
print(response.text)
print(response.headers)
For the requests library in python, the data object takes a python dict object, not a JSON string. If you were to edit your code to:
import requests
import json
url = "http://172.125.169.21/api/user/login"
payload = {"name": "test5", "password": "Hello123"}
headers = {'Content-Type': "application/json"}
response = requests.request("POST", url, json=payload, headers=headers)
# the json parameter should handle encoding for you
print(response.text)
print(response.headers)
Cookies are available to you in the cookies parameter of the response object. See the requests documentation for more information.
print(json.dumps(response.cookies, separators=(",",":"), indent = 4))
This should pretty print the cookie(s) you've received. You can use requests' session handling abilities or a variable to store this information, however you choose. We'll save these cookies to a requests cookiejar:
cookies = response.cookies
and we'll use those cookies in the authorization check or any other requests:
auth_check_url = "172.125.169.21/api/user/checkLogin"
response = requests.get(auth_check_url, cookies=cookies)
print(response.text)

Making a successful Python HTTP POST Request

I am trying to write a python script that will make a request to a desktop application listening to 8080 port. The below is the code that I use to make the request.
import requests
payload = {"url":"abcdefghiklmnopqrstuvwxyz=",
"password":"qertyuioplkjhgfdsazxvnm=",
"token":"abcdefghijklmn1254786=="}
headers = {'Content-Type':'application/json'}
r = requests.post('http://localhost:9015/login',params = payload, headers=headers)
response = requests.get("http://localhost:9015/login")
print(r.status_code)
After making the request, I get a response code of 401.
However, when I try the same using the Postman app, I get a successful response. The following are the details I give in Postman:
URL: http://localhost:9015/login
METHOD : POST
Headers: Content-Type:application/json
Body: {"url":"abcdefghiklmnopqrstuvwxyz=",
"password":"qertyuioplkjhgfdsazxvnm=",
"token":"abcdefghijklmn1254786=="}
Can I get some suggestions on where I am going wrong with my python script?
You pass params, when you should pass data, or, even better, json for setting Content-Type automatically. So, it should be:
import json
r = requests.post('http://localhost:9015/login', data=json.dumps(payload), headers=headers)
or
r = requests.post('http://localhost:9015/login', json=payload)
(params adds key-value pairs to query parameters in the url)

Categories

Resources