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.
JavaScript
x
21
21
1
##/* Request for access token */
2
3
$base_url = "myurl";
4
$client_id="1234";
5
$client_secret="5678";
6
7
$client_details = "${client_id}:${client_secret}";
8
9
$context = stream_context_create(array(
10
'http' => array(
11
'method' => 'POST',
12
'header' => "Content-Type: application/x-www-form-urlencodedrn" .
13
"Authorization : Basic $client_detailsrn",
14
'content' => "grant_type=client_credentials"
15
)
16
));
17
18
$response = file_get_contents($base_url.'/apis/oauth2/Token.php', false, $context);
19
$res = json_decode($response);
20
$token = $res->access_token;
21
This is what i am trying to do in Python.
My Python code is:
JavaScript
1
14
14
1
import urllib
2
import sys
3
import json
4
import requests
5
6
base_url = 'myurl'
7
client_id='1234'
8
client_secret='5678'
9
10
response = requests.post(base_url+'/apis/oauth2/Token.php',
11
auth=(client_id, client_secret))
12
13
print(response.json())
14
but this is not working
Python is returning:
JavaScript
1
2
1
{'error': 'invalid_request', 'error_description': 'The grant type was not specified in the request'}
2
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?
Advertisement
Answer
I managed to solve my problem. This is the code:
JavaScript
1
15
15
1
import urllib
2
import sys
3
import json
4
import requests
5
6
base_url = 'https://myurl.com'
7
client_id='1234'
8
client_secret='5678'
9
grant_type='client_credentials'
10
11
response = requests.post(base_url+'/apis/oauth2/Token.php',
12
auth=(client_id, client_secret),
13
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
14
print(response.json())
15