Ok, it just took me quite some time to figure out how to get (private) reviews data from the Trustpilot API using python.
Yes, they have docs:
https://developers.trustpilot.com/
https://developers.trustpilot.com/authentication
But for some reason it's still never right away clear to me how to get an access token, and how to use that access token to get reviews data from the api.
So: can you provide me a clear python starter script, that gets an access token from the Trustpilot api, and then gets reviews data from the api?
Follow the steps below to get the private review data of your company from the Trustpilot API:
import base64
import requests
# you need to have an api key and secret (created in the UI) to query the reviews of your company
API_KEY = "your_api_key"
API_SECRET = "your_secret"
# you need to base64 encode your api key in the following way:
b64encode_key_secret = base64.b64encode(f"{API_KEY}:{API_SECRET}".encode("ascii")).decode("ascii")
endpoint_access_token = "https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken"
headers_access_token = {
"Authorization": f"Basic {b64encode_key_secret}", # mandatory
"Content-Type": "application/x-www-form-urlencoded", # mandatory
}
payload_access_token = "grant_type=client_credentials" # mandatory
response = requests.post(
url=endpoint_access_token,
headers=headers_access_token,
data=payload_access_token,
).json()
access_token = response["access_token"] # access tokens are 100 hours valid
# you need to know the business_unit_id of your company to get your reviews
business_unit_id = "your business unit id"
# get reviews using the access_token
endpoint_reviews = f"https://api.trustpilot.com/v1/private/business-units/{business_unit_id}/reviews"
headers = {
"Authorization": f"Bearer {access_token}", # mandatory
}
params = {
"perPage": 100 # maximum number of reviews you can get from 1 request (higher number will give error)
}
response = requests.get(url=endpoint_reviews, headers=headers, params=params)
reviews = response.json()
There is also a python client from Trustpilot itself: https://github.com/trustpilot/python-trustpilot
You need api key, api secret, username and password for that to work.