Search code examples
pythonibm-watsonpersonality-insights

IBM Watson Personality Insights token Authentication Python


Can anyone please let me know the process to generate and use the token for IBM personality insights.

Watson Personality Insights token


Solution

  • For this, you need to use HTTP GET request to the token with Python and get the token.

    one.py:

    def generateToken(username, password):
    
    r = requests.get("https://gateway.watsonplatform.net/authorization/api/v1/token?url=https://gateway.watsonplatform.net/personality-insights/api", auth=(username, password))
            if r.status_code == requests.codes.ok:
                return r.text
    
    def personalityRequest(text, token):
        base_url='https://gateway.watsonplatform.net/etc/etc....'
        headers = {'X-Watson-Authorization-Token': token, 'Content-Type': 'yourContextType'}
        r = requests.post(base_url, headers=headers, data={'body': text})
        return r.text
    

    two.py:

    token = one.generateToken()
    ret = one.personalityRequest("your Text analyze...", token)
        print(ret)
    

    Obs.: "Tokens have a time to live (TTL) of one hour, after which you can no longer use them to establish a connection with the service. Existing connections already established with the token are unaffected by the timeout. An attempt to pass an expired or invalid token elicits an HTTP 401 Unauthorized status code from DataPower. Your application code needs to be prepared to refresh the token in response to this return code."

    See the official documentation about Tokens with IBM Watson here.

    See the official reference about using Authorization inside the SDK here.