Hey there, fellow JavaScript devs! Ready to dive into the world of Odoo CRM API? Let's get our hands dirty with some data syncing for user-facing integrations. Buckle up!
First things first, let's get our environment ready. You'll need axios for making HTTP requests. Pop this into your terminal:
npm install axios
Now, let's set up our API credentials:
const axios = require('axios'); const odooApi = axios.create({ baseURL: 'https://your-odoo-instance.com/api', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-api-key-here' } });
Odoo uses API keys for authentication. Once you've got your key, you're good to go. No need for complex OAuth flows here!
Want to grab some customer info? Here's how:
async function getCustomers(limit = 10) { try { const response = await odooApi.get('/res.partner', { params: { limit: limit, fields: ['name', 'email', 'phone'] } }); return response.data; } catch (error) { console.error('Oops! Something went wrong:', error); } }
Adding a new lead? Easy peasy:
async function createLead(leadData) { try { const response = await odooApi.post('/crm.lead', { data: leadData }); return response.data; } catch (error) { console.error('Houston, we have a problem:', error); } } // Usage createLead({ name: 'Potential Big Fish', email_from: '[email protected]', phone: '+1234567890' });
Linking contacts to companies? We've got you covered:
async function linkContactToCompany(contactId, companyId) { try { await odooApi.put(`/res.partner/${contactId}`, { data: { parent_id: companyId } }); console.log('Link successful!'); } catch (error) { console.error('Link failed:', error); } }
Always wrap your API calls in try-catch blocks. And remember, Odoo has rate limits, so don't go too crazy with those requests!
function handleApiError(error) { if (error.response) { console.error('Odoo says no:', error.response.data); } else if (error.request) { console.error('No response from Odoo. Is it napping?'); } else { console.error('Something went wrong:', error.message); } }
Webhooks are your friend for real-time updates. Here's a simple Express server to listen for Odoo webhooks:
const express = require('express'); const app = express(); app.post('/odoo-webhook', express.json(), (req, res) => { const { model, id, action } = req.body; console.log(`${action} on ${model} with ID ${id}`); // Handle the update res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook listener ready!'));
There you have it! You're now equipped to read and write data like a pro using the Odoo CRM API. Remember, practice makes perfect, so don't be afraid to experiment and build some cool integrations.
Keep coding, stay curious, and may your API calls always return 200 OK! 🚀