Bearer token error

oauth
api

#1

I used Python to access bearer token and it returned the following error, can anyone please help?
import requests

OAUTH2_TOKEN_URL = 'https://api.twitter.com/oauth2/token'


def get_access_token(bearer_credentials):
    headers = {
        'Authorization': 'Basic {}'.format(bearer_credentials),
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
    data = 'grant_type=client_credentials'

    response = requests.post(OAUTH2_TOKEN_URL, data=data, headers=headers)

    if response.status_code != requests.codes.ok:
        raise Exception('Invalid request or invalid credentials')

    response_body = response.json()
    if response_body.get('token_type', '') == 'bearer':
        access_token = response_body.get('access_token')
        print(access_token)
        return access_token
    else:
        raise Exception(('Invalid token type of returned access token. Token type')
                       ('is not bearer.'))
print(get_access_token('here is my bearer credential'))

The error was

C:\Users\worknehYA\.virtualenvs\bearer\Scripts\python.exe C:/Users/worknehYA/PycharmProjects/bearer/bearer3.py
Traceback (most recent call last):
  File "C:/Users/worknehYA/PycharmProjects/bearer/bearer3.py", line 26, in <module>
    print(get_access_token('VzZPMm91cFVaN3hlM2hScTg1U1g5UUQ4cjowUllmTW5qOUR4UGdHNXgwZzZCQXZySVY0NzEyemlj\nZE91RzNCMDdBZFdsdEl4WjB0Sw=='))
  File "C:/Users/worknehYA/PycharmProjects/bearer/bearer3.py", line 13, in get_access_token
    response = requests.post(OAUTH2_TOKEN_URL, data=data, headers=headers)
  File "C:\Users\worknehYA\.virtualenvs\bearer\lib\site-packages\requests\api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\worknehYA\.virtualenvs\bearer\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\worknehYA\.virtualenvs\bearer\lib\site-packages\requests\sessions.py", line 494, in request
    prep = self.prepare_request(req)
  File "C:\Users\worknehYA\.virtualenvs\bearer\lib\site-packages\requests\sessions.py", line 437, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Users\worknehYA\.virtualenvs\bearer\lib\site-packages\requests\models.py", line 306, in prepare
    self.prepare_headers(headers)
  File "C:\Users\worknehYA\.virtualenvs\bearer\lib\site-packages\requests\models.py", line 440, in prepare_headers
    check_header_validity(header)
  File "C:\Users\worknehYA\.virtualenvs\bearer\lib\site-packages\requests\utils.py", line 869, in check_header_validity
    raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
requests.exceptions.InvalidHeader: Invalid return character or leading space in header: Authorization

Process finished with exit code 1


#2

What does your Authorization header contain?


#3

Basic


#4

I now managed to get the token using a ruby script