Back

Reading and Writing Data Using the Trustpilot API

Aug 2, 20246 minute read

Hey there, fellow JavaScript enthusiasts! Ready to dive into the world of Trustpilot API integration? Let's get our hands dirty with some code and learn how to sync data for a user-facing integration that'll make your app shine.

Authentication: Your Golden Ticket

First things first, we need to get you authenticated. Head over to Trustpilot's developer portal and grab your API credentials. We'll be using OAuth 2.0, so buckle up!

Here's a quick snippet to manage your tokens:

const axios = require('axios'); async function getAccessToken(clientId, clientSecret) { const response = await axios.post('https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken', { grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }); return response.data.access_token; }

Reading Data: Get Those Reviews!

Now that we're in, let's fetch some reviews. We'll use Axios for our requests because, well, it's awesome.

async function getReviews(businessUnitId, accessToken) { const response = await axios.get(`https://api.trustpilot.com/v1/business-units/${businessUnitId}/reviews`, { headers: { Authorization: `Bearer ${accessToken}` } }); return response.data.reviews; }

Writing Data: Spread the Love

Time to invite customers and respond to reviews. Here's how you can invite a customer to leave a review:

async function inviteCustomer(businessUnitId, accessToken, customerData) { try { await axios.post(`https://invitations-api.trustpilot.com/v1/private/business-units/${businessUnitId}/invitations`, customerData, { headers: { Authorization: `Bearer ${accessToken}` } }); console.log('Invitation sent successfully!'); } catch (error) { console.error('Oops! Something went wrong:', error.response.data); } }

Syncing Data: Stay Up-to-Date

Webhooks are your best friend for real-time updates. Here's a simple Express endpoint to handle incoming webhooks:

const express = require('express'); const app = express(); app.post('/trustpilot-webhook', express.json(), (req, res) => { const { eventName, businessUnitId, reviewId } = req.body; console.log(`New event: ${eventName} for business ${businessUnitId}`); // Handle the event (e.g., fetch the new review, update your database) res.sendStatus(200); });

Error Handling and Edge Cases: Expect the Unexpected

Always be prepared for API hiccups. Here's a handy wrapper for your API calls:

async function apiCall(fn) { try { return await fn(); } catch (error) { if (error.response && error.response.status === 429) { console.log('Rate limited. Retrying in 5 seconds...'); await new Promise(resolve => setTimeout(resolve, 5000)); return apiCall(fn); } throw error; } }

Optimizing Performance: Speed It Up!

Caching is your secret weapon. Let's implement a simple in-memory cache:

const cache = new Map(); async function getCachedReviews(businessUnitId, accessToken) { const cacheKey = `reviews_${businessUnitId}`; if (cache.has(cacheKey)) { return cache.get(cacheKey); } const reviews = await getReviews(businessUnitId, accessToken); cache.set(cacheKey, reviews); setTimeout(() => cache.delete(cacheKey), 5 * 60 * 1000); // Cache for 5 minutes return reviews; }

User-facing Integration: Show It Off

Time to display those shiny reviews! Here's a simple React component to get you started:

function TrustpilotReviews({ businessUnitId }) { const [reviews, setReviews] = useState([]); useEffect(() => { async function fetchReviews() { const accessToken = await getAccessToken(CLIENT_ID, CLIENT_SECRET); const reviews = await getCachedReviews(businessUnitId, accessToken); setReviews(reviews); } fetchReviews(); }, [businessUnitId]); return ( <div className="trustpilot-reviews"> {reviews.map(review => ( <div key={review.id} className="review"> <h3>{review.title}</h3> <p>{review.text}</p> <div>{review.stars} stars</div> </div> ))} </div> ); }

Testing and Debugging: Trust, but Verify

Always test in the sandbox environment first! Here's a quick Jest test to get you started:

test('fetches reviews successfully', async () => { const accessToken = await getAccessToken(SANDBOX_CLIENT_ID, SANDBOX_CLIENT_SECRET); const reviews = await getReviews(SANDBOX_BUSINESS_UNIT_ID, accessToken); expect(reviews).toBeDefined(); expect(reviews.length).toBeGreaterThan(0); });

Wrapping Up

And there you have it, folks! You're now equipped to read and write data like a Trustpilot pro. Remember to always check the official docs for the latest updates, and don't be afraid to experiment. Happy coding, and may your integration be ever trustworthy!