I am very beginner at Python scripting and i have a problem.
I am trying to rewrite PHP code to Python to get Access token from API for further use.
##/* Request for access token */
$base_url = "myurl";
$client_id="1234";
$client_secret="5678";
$client_details = "${client_id}:${client_secret}";
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
"Authorization : Basic $client_details\r\n",
'content' => "grant_type=client_credentials"
)
));
$response = file_get_contents($base_url.'/apis/oauth2/Token.php', false, $context);
$res = json_decode($response);
$token = $res->access_token;
This is what i am trying to do in Python.
My Python code is:
import urllib
import sys
import json
import requests
base_url = 'myurl'
client_id='1234'
client_secret='5678'
response = requests.post(base_url+'/apis/oauth2/Token.php',
auth=(client_id, client_secret))
print(response.json())
but this is not working
Python is returning:
{'error': 'invalid_request', 'error_description': 'The grant type was not specified in the request'}
I know that i am missing everything from the context variable from PHP Code. Do you know if there is a python method to create context like stream_context_create in PHP or maybe could you give me some tips how can i do it?
I managed to solve my problem. This is the code:
import urllib
import sys
import json
import requests
base_url = 'https://myurl.com'
client_id='1234'
client_secret='5678'
grant_type='client_credentials'
response = requests.post(base_url+'/apis/oauth2/Token.php',
auth=(client_id, client_secret),
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
print(response.json())