Hey there, fellow code wranglers! Ready to dive into the world of freelancing APIs? Today, we're going to walk through integrating the Freelancer API into your JavaScript project. This powerhouse of an API opens up a whole new world of possibilities for your apps, from project searching to bid placement. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get our project off the ground:
mkdir freelancer-api-integration cd freelancer-api-integration npm init -y npm install axios dotenv
Create a .env
file for your API key:
FREELANCER_API_KEY=your_api_key_here
Freelancer uses OAuth 2.0. Here's a quick implementation:
const axios = require('axios'); require('dotenv').config(); const getAccessToken = async () => { try { const response = await axios.post('https://www.freelancer.com/api/v1/auth/token', { grant_type: 'client_credentials', client_id: process.env.FREELANCER_API_KEY, client_secret: process.env.FREELANCER_API_SECRET }); return response.data.access_token; } catch (error) { console.error('Authentication failed:', error); } };
Now that we're authenticated, let's make some requests:
const makeApiRequest = async (endpoint, method = 'GET', data = null) => { const accessToken = await getAccessToken(); try { const response = await axios({ method, url: `https://www.freelancer.com/api/v1/${endpoint}`, headers: { 'Authorization': `Bearer ${accessToken}` }, data }); return response.data; } catch (error) { console.error('API request failed:', error); } };
Search for projects:
const searchProjects = async (query) => { return await makeApiRequest(`projects/0.1/projects/search?query=${query}`); };
Post a project:
const postProject = async (projectData) => { return await makeApiRequest('projects/0.1/projects', 'POST', projectData); };
Place a bid:
const placeBid = async (projectId, bidData) => { return await makeApiRequest(`projects/0.1/bids`, 'POST', { ...bidData, project_id: projectId }); };
Fetch user profile:
const getUserProfile = async (userId) => { return await makeApiRequest(`users/0.1/users/${userId}`); };
Setting up webhooks is crucial for real-time updates. Here's a basic Express server to handle webhook events:
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const event = req.body; // Handle the event based on its type console.log('Received webhook event:', event); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
Implement retry logic and respect rate limits:
const makeApiRequestWithRetry = async (endpoint, method = 'GET', data = null, maxRetries = 3) => { for (let i = 0; i < maxRetries; i++) { try { return await makeApiRequest(endpoint, method, data); } catch (error) { if (error.response && error.response.status === 429) { // Rate limited, wait before retrying await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } else { throw error; } } } throw new Error(`Failed after ${maxRetries} retries`); };
Don't forget to test! Here's a quick Jest test to get you started:
test('searchProjects returns results', async () => { const results = await searchProjects('javascript'); expect(results.projects.length).toBeGreaterThan(0); });
And there you have it! You're now armed with the knowledge to integrate the Freelancer API into your JavaScript projects. Remember, this is just scratching the surface – there's a whole world of features to explore in the Freelancer API documentation.
Now go forth and build something awesome! Happy coding! 🚀