Alexandru Marton
Alexandru Marton

Reputation: 65

Using Python to test HTTP APIs

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')

Upvotes: 1

Views: 3804

Answers (1)

Cyrbil
Cyrbil

Reputation: 6478

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

Upvotes: 2

Related Questions