curl - Get access token from Paypal in Python - Using urllib2 or requests library -


curl

curl -v https://api.sandbox.paypal.com/v1/oauth2/token \   -h "accept: application/json" \   -h "accept-language: en_us" \   -u "client_id:client_secret" \   -d "grant_type=client_credentials" 

parameters: -u take client_id:client_secret

here pass client_id , client_secret, it's worked in curl.

i trying same things implement on python

python

import urllib2 import base64 token_url = 'https://api.sandbox.paypal.com/v1/oauth2/token' client_id = '.....' client_secret = '....'  credentials = "%s:%s" % (client_id, client_secret) encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")  header_params = {     "authorization": ("basic %s" % encode_credential),     "content-type": "application/x-www-form-urlencoded",     "accept": "application/json" } param = {     'grant_type': 'client_credentials', }  request = urllib2.request(token_url, param, header_params) response = urllib2.urlopen(request) print "response______", response 

traceback:

result = urllib2.urlopen(request)

 httperror: http error 400: bad request 

can inform me whats wrong python code?

i suggest using requests:

import requests import base64  client_id = "" client_secret = ""  credentials = "%s:%s" % (client_id, client_secret) encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")  headers = {     "authorization": ("basic %s" % encode_credential),     'accept': 'application/json',     'accept-language': 'en_us', }  param = {     'grant_type': 'client_credentials', }  url = 'https://api.sandbox.paypal.com/v1/oauth2/token'  r = requests.post(url, headers=headers, data=param)  print(r.text) 

Comments