Skip to content
Advertisement

GET Access token from API (oauth2)

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-urlencodedrn" .
                "Authorization : Basic $client_detailsrn",
    '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?

Advertisement

Answer

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())
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement