1

I'm fairly new to Python programming and I don't know all the libraries needed for the following.

I would like to use Python to test some HTTP APIs. Mainly I want to use OAuth and make a few JSON calls. The APIs in question can be found on: https://developers.trustpilot.com/authentication and the generate product review link (I can only use one link)

I want to authenticate myself and then generate a product review link in one step. So far I've been using the Advanced REST client (ARC) to make these calls individually. I could also use .arc files if you think it's easier.

The idea would be make these calls successively in one go. So it would be something along the lines:

1) Make the authentication call.

The HTTP Method looks like this: https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken Method Post:

Header Authorization: Basic Base64encode(APIkey:Secret) Content-Type: application/x-www-form-urlencoded

Payload: grant_type=password&[email protected]&password=SomePass

Translate this bit into Python basically.

1.a) Add a header to the call

Header Authorization: base64encode hash Content-Type: application/x-www-form-urlencoded

1.b) Add a payload to the call

Payload: grant_type=password&username

4) Receive the token from call made in step 1) (Result is format)

"access token": Auth_token

5) Take the token and use it in creating a product review.

5.a) Add the token in the header

Header: Authorization: Bearer Auth_token

6.a) Add a JSON payload to the call made in step 5.

Here's the code I have so far:

Import requests

header = {'Authorization: Basic NnNrQUprTWRHTU5VSXJGYXBVRGxack1oT01oTUFRZHI6QTFvOGJjRUNDdUxBTmVqUQ==}','Content-Type: application/x-www-form-urlencoded'}
payload = {'grant_type=password&[email protected]&password=SomePassword'}
r = requests.post('https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken', headers=header, params=payload )

Ideally I want to create the requests.post(url, header, payload) and then return what the server answers in JSON format. I think that print r.text would do the last part.

So this is the code I have writtent (that works now):

import requests
import getpass
import json
from requests.auth import HTTPBasicAuth

header = {'grant_type':'password' , 'username':'[email protected]', 'password':'YourPassword'}
username= "YOURAPIKEY" #APIKey
password= "YOURSECRET" #Secret
res = requests.post(
    'URL/v1/oauth/oauth-business-users-for-applications/accesstoken',
    auth=HTTPBasicAuth(username, password),  # basic authentication
    data=header)

#print(res.content) #See content of the call result.

data = res.json()  # get response as parsed json (will return a dict)
auth_token = data.get('access_token')
3
  • json.loads(), json.dumps() are quite good start. Also requests accept named argument headers as dict. Commented Mar 24, 2016 at 8:54
  • Instead of implementing the OAuth2 flow yourself, have you looked at e.g. Requests-OAuthLib? Their documentation has a few tutorials for different OAuth providers. Commented Mar 24, 2016 at 8:54
  • I was hoping to just Authenticate with the HTTP Post request. Normally there is an Authorization part comprised of a base64 encoded APIKey and Secret, along with the user and password. Commented Mar 24, 2016 at 10:02

1 Answer 1

2

requests can do all what you ask without any work from your part.

See the doc for authentication, parameters, json output, json input

Make the authentication call.

import requests
import getpass

from requests.auth import HTTPBasicAuth

username = raw_input('Username: ')
password = getpass.getpass('Password: ')

res = requests.post(
    'https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken',
    auth=HTTPBasicAuth(username, password),  # basic authentication
    params={  # url parameters
        'grant_type': 'password',
        'username': '[email protected]',
        'password': 'SomePassword'
    })

Receive the token from call made in step 1) (Result is format)

# res = requests.post.....
data = res.json()  # get response as parsed json (will return a dict)
auth_token = data.get('access token')

Take the token and use it in creating a product review.

request.post(
    '.../product_review',
    headers={
        'Authorization': 'Bearer ' + auth_token
    },
    json={'my': 'payload'})  # send data as json
Sign up to request clarification or add additional context in comments.

7 Comments

In the Authentication process for the HTTP Post call I also have an authorization part in the header. It's comprised of an APIKey and Secret base64 encoded. So the header would have something like Authorization: Basic base64hash. Is there any way to provide those as the header?
HTTPBasicAuth(username, password) will be your API KEY and API SECRET. requests will put it in the header Authorization correctly.
Will it also do the base64encode automatically? I suspect I need to do this separately. The HTTP Call I make looks like this: The HTTP Method looks like this: api.trustpilot.com/v1/oauth/… Method Post Header Authorization: Basic Base64encode(APIkey:Secret) Content-Type: application/x-www-form-urlencoded Payload: grant_type=password&[email protected]&password=SomePass
Is will be base64 encoded as base64(API KEY:API SECRET) just like the api wants :).
I see. So where do I input the [email protected] and password for said username? If I read the code correctly, the params= part will just use the APIKey and Secret. Or do I just hardcode them in the param section? I also get an error when I try to run the code: 'Authorization': 'Bearer ' + auth_token TypeError: Can't convert 'NoneType' object to str implicitly
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.