Search code examples
pythonpython-3.xapipython-requeststoken

How to get token from API with Python?


I need to get token to connect to API. Tried with python this:

import requests, base64
url = 'https://api-b2b.alzura.com/common/login'
token_req = base64.b64encode(b'name:passwd').decode()
headers = {'Authorization': str(token_req)}
req = requests.post(url, headers=headers)
print(req)

And got <Response [400]>, but no token. :D I have read this post part about python, but it dint't work for me.

Looks like I does it completely wrong. What should I do/learn/read?

Thank you for your time!

UPDATE It should be a basic auth, and it looks like there is no need any user secrets. Here is little manual from developer:

Get a login token and expire date. Returns the X-AUTH-TOKEN which is required for authentication of the remaining endpoints. Authentication for this endpoint is basic auth. For authentication, an authentication-header formatted as 'Alzura ID:Password' must be transmitted as a base64-encoded string.


Solution

  • First note that a token must be obtained from the server ! A token is required to make some API calls due to security concerns. There are usually at least two types of tokens:

    • Access token: You use it to make API calls (as in the Authorization header above). But this token usually expires after a short period of time.
    • Refresh token: Use this token to refresh the access token after it has expired.

    You should use requests-oauthlib in addition with requests.
    https://pypi.org/project/requests-oauthlib/
    But first, read the available token acquisition workflows:
    https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#available-workflows
    and choose the right workflow that suits your purposes. (The most frequently used is Web App workflow)
    Then, implement the workflow in your code to obtain the token. Once a valid token is obtained you can use it to make various API calls.

    As a side note: be sure to refresh token if required.