give me code in nodejs that hits the api of endpoint…
- User
give me code in nodejs that hits the api of endpoint https://api.hubapi.com/crm/v3/objects/contacts, method =post,body= { 2 "properties": 3 { 4 "email": "", 5 "firstname": "", 6 "lastname": "", 7 "phone": "", 8 "zip": "", 9 "city": "", 10 "lifecyclestage": "lead", 11 "brand": "Ultraviolette", 12 "contact_type": "BUYER_B2C", 13 "message": ""//intent (testride, enquiry, configure) 14 } 15 } , extract these fields from the incoming event, this code will be a aws lambda function
Assistant
Here's a Node.js AWS Lambda function that hits the HubSpot API endpoint to create a contact, extracting fields from the incoming event:
const axios = require('axios'); exports.handler = async (event) => { try { // Extract fields from the incoming event const { email, firstname, lastname, phone, zip, city, message, brand = "Ultraviolette", contact_type = "BUYER_B2C", lifecyclestage = "lead" } = JSON.parse(event.body) || {}; // Validate required fields if (!email) { return { statusCode: 400, body: JSON.stringify({ error: "Email is required" }) }; } // Prepare the request body const requestBody = { properties: { email, firstname, lastname, phone, zip, city, lifecyclestage, brand, contact_type, message } }; // HubSpot API configuration const hubspotApiKey = process.env.HUBSPOT_API_KEY; // Store this in Lambda environment variables const apiUrl = 'https://api.hubapi.com/crm/v3/objects/contacts'; // Make the API request const response = await axios.post(apiUrl, requestBody, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${hubspotApiKey}` } }); // Return the response from HubSpot return { statusCode: 200, body: JSON.stringify(response.data) }; } catch (error) { console.error('Error:', error); return { statusCode: error.response?.status || 500, body: JSON.stringify({ error: error.message, details: error.response?.data || error.message }) }; } };Important Notes:
-
Environment Variables: Store your HubSpot API key in the Lambda environment variables (not in the code) with the name
HUBSPOT_API_KEY. -
Dependencies: You'll need to include the
axiospackage in your Lambda deployment package. You can do this by:- Creating a
node_modulesfolder with axios installed - Or using a Lambda layer with axios
- Creating a
-
IAM Permissions: Ensure your Lambda function has the necessary permissions to make outbound HTTP requests.
-
Error Handling: The code includes basic error handling, but you might want to expand it based on your specific requirements.
-
Input Validation: The code checks for required fields (email), but you might want to add more validation as needed.
-
Testing: Test this function thoroughly with different input scenarios before deploying to production.
To deploy this, you'll need to:
- Create a Lambda function in AWS
- Add the code above
- Set up the environment variable for the API key
- Configure the appropriate trigger (API Gateway, SNS, etc.) based on your needs
-