Get access token from Paypal in Python - Using urllib2 or requests library
Question: ### 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 I pass my `client_id` and `client_secret`, It's worked properly in cURL.

I am trying to 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 you inform me whats wrong with my python code?


Answer: I would 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)
    

