Hey there, fellow JavaScript enthusiasts! Ready to dive into the world of the Freelancer API? Let's get our hands dirty with some code and learn how to sync data for a user-facing integration. Buckle up!
First things first, we need to get that sweet, sweet access token. The Freelancer API uses OAuth 2.0, so let's set it up:
const getAccessToken = async (code) => { const response = await fetch('https://www.freelancer.com/api/oauth/token', { method: 'POST', body: new URLSearchParams({ grant_type: 'authorization_code', code, client_id: YOUR_CLIENT_ID, client_secret: YOUR_CLIENT_SECRET, }), }); return response.json(); };
Pro tip: Don't forget to refresh that token before it expires!
Now that we're in, let's grab some data. Here's how you can fetch a user's profile:
const getUserProfile = async (accessToken) => { const response = await fetch('https://www.freelancer.com/api/users/0.1/self', { headers: { 'Authorization': `Bearer ${accessToken}` }, }); return response.json(); };
Easy peasy, right? You can use similar patterns to get project listings, bid info, and more.
Time to interact with the platform. Here's how you can submit a bid:
const submitBid = async (accessToken, projectId, amount, description) => { const response = await fetch('https://www.freelancer.com/api/projects/0.1/bids/', { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ project_id: projectId, amount, description }), }); return response.json(); };
Want real-time updates? Webhooks are your new best friend. Here's a quick Express.js setup:
app.post('/webhook', (req, res) => { const event = req.body; // Handle the event based on its type switch (event.type) { case 'project.awarded': // Update your local data break; // Handle other event types } res.sendStatus(200); });
Remember to play nice with rate limits and pagination. Your API calls will thank you!
APIs can be moody. Let's handle those tantrums gracefully:
const makeApiCall = async (url, options) => { try { const response = await fetch(url, options); if (!response.ok) { throw new Error(`API call failed: ${response.status}`); } return response.json(); } catch (error) { console.error('API Error:', error); // Implement retry logic or user notification here } };
And there you have it! You're now equipped to build some awesome integrations with the Freelancer API. Remember, the key to mastering any API is practice and patience. So go forth and code, my friends!
Need more details? Check out the Freelancer API Documentation. Happy coding!