APIs & Integrations

Oldu
Member

Associations v4 basicApi issue

SOLVE

Hi!

Im new to hubspot crm, but trying to make one simple thing. I have created the extension that just make document files, now i need data for this files. I want to get it from Deal associations. I have custom object - it represents the products associated with the deal. So, everything I want just to fetch the list of the products. 

My card use call to serverless function, main data it passes without problem, so I assume I make it works. But I stuck with getting the products. I tried this request right in the sandobx of documenation 
/crm/v4/objects/{objectType}/{objectId}/associations/{toObjectType}

I put my token and objectType, objectId and toObjectType to the sandbox and it works. I see the results in sandbox below. So, I copied the code from it to my serverless function and I can't make a request, because getting 
ERROR - TypeError: Cannot read properties of undefined (reading 'basicApi')
at exports.main (/var/task/test.js:66:47)
at exports.hubspot_handler [as handler] (/var/task/hubspotHandler.js:20:34)
at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1187:29)

I google a lot and find that there was a problem with Node.js, but it was in 2023. So, I hope they have fixed it already. I tried to create a simple fetch requests to v3 and v4 api and didn't get results in it. All the times some kind of errors. So, can somebody please share how you guys fetching the associations details with hubspot SDK or without. 

I even tried this:

async function getAssociatedRecords({
  objectType,
  objectId,
  toObjectType,
  token,
}) {
  const path = `/crm/v4/objects/${objectType}/${objectId}/associations/${toObjectType}`;

  return new Promise((resolve, reject) => {
    const options = {
      method: "GET",
      hostname: "api.hubapi.com",
      path,
      headers: {
        accept: "application/json",
        "content-type": "application/json",
        authorization: "Bearer " + token,
      },
    };

    const req = https.request(options, (res) => {
      let chunks = [];

      res.on("data", (chunk) => chunks.push(chunk));
      res.on("end", () => {
        const body = Buffer.concat(chunks).toString();

        console.log(" Status Code:", res.statusCode);
        console.log(" Raw Body:", body);

        if (!body || body.trim() === "") {
          return reject({
            message: "Empty response body",
            statusCode: res.statusCode,
          });
        }

        try {
          const parsed = JSON.parse(body);
          resolve(parsed);
        } catch (err) {
          reject({ message: "Failed to parse JSON", raw: body });
        }
      });
    });

    req.on("error", (err) => reject(err));
    req.end();
  });
}


but still no luck 

0 Upvotes
1 Accepted solution
MichaelMa
Solution
Contributor

Associations v4 basicApi issue

SOLVE

This is the code I'm using on the CRM Card I'm building (it's a serverless function but the code should be fine anywhere). In general, I prefer to use BatchApi over BasicApi because I can keep the data format consistent across all functions (instead of using one for when I retrieve record and another when I retrieve multiple records). I have no idea if there's a speed benefit for one vs the other.

 

Media Plans is our custom object which is converted to the p_media_plans object name. So you can see the first function, getTicketAssociationsById, simply prepares the payload (ticket id) and then calls the function to retrieve the data. All the data gets returned to the function that called it.

 

 

/*****
Retrieve all associations of a ticket that we need
*****/
async function getTicketAssociationsById (ticket_id) {
	const payload = {"inputs": [ { "id": ticket_id }]};
	
	let companies = await getAssociations( "tickets", "company", payload );
	let contacts = await getAssociations( "tickets", "contacts", payload );
	let deals = await getAssociations( "tickets", "deals", payload );
	let media_plans = await getAssociations( "tickets", "p_media_plans", payload );
	
	return ( {"companies": companies, "contacts": contacts, "deals": deals, "media_plans": media_plans } );
}
	
/*****
Associations Call
*****/
async function getAssociations (source, target, data) {
  // API Call
  try {
    const results = await hubspotClient.crm.associations.v4.batchApi.getPage(source, target, data)
    return results.results
  } catch (e) {
    console.log(e)
  }
}

 

 

Since I don't know your code that is returning the error, hard to tell what's wrong. But unknown function usually means there's something wrong in the function you're trying to call.

 

If the code that you pulled is not working, which it should, you probably need to verify the data you're presenting.

 

I would open up something like Postman and test the API request directly.

 

Eg,

 

If you run a GET request on:

https://api.hubapi.com/crm/v4/objects/deals/12345/associations/tickets

 

Where 12345 is your deal, you would get tickets associated with the deal.

 

Let's say your custom object name is Products so your object name should be something like p_products, you would do something like:

https://api.hubapi.com/crm/v4/objects/deals/12345/associations/p_products

 

Which should retrieve all the products associated with the deal.

 

View solution in original post

0 Upvotes
2 Replies 2
MichaelMa
Solution
Contributor

Associations v4 basicApi issue

SOLVE

This is the code I'm using on the CRM Card I'm building (it's a serverless function but the code should be fine anywhere). In general, I prefer to use BatchApi over BasicApi because I can keep the data format consistent across all functions (instead of using one for when I retrieve record and another when I retrieve multiple records). I have no idea if there's a speed benefit for one vs the other.

 

Media Plans is our custom object which is converted to the p_media_plans object name. So you can see the first function, getTicketAssociationsById, simply prepares the payload (ticket id) and then calls the function to retrieve the data. All the data gets returned to the function that called it.

 

 

/*****
Retrieve all associations of a ticket that we need
*****/
async function getTicketAssociationsById (ticket_id) {
	const payload = {"inputs": [ { "id": ticket_id }]};
	
	let companies = await getAssociations( "tickets", "company", payload );
	let contacts = await getAssociations( "tickets", "contacts", payload );
	let deals = await getAssociations( "tickets", "deals", payload );
	let media_plans = await getAssociations( "tickets", "p_media_plans", payload );
	
	return ( {"companies": companies, "contacts": contacts, "deals": deals, "media_plans": media_plans } );
}
	
/*****
Associations Call
*****/
async function getAssociations (source, target, data) {
  // API Call
  try {
    const results = await hubspotClient.crm.associations.v4.batchApi.getPage(source, target, data)
    return results.results
  } catch (e) {
    console.log(e)
  }
}

 

 

Since I don't know your code that is returning the error, hard to tell what's wrong. But unknown function usually means there's something wrong in the function you're trying to call.

 

If the code that you pulled is not working, which it should, you probably need to verify the data you're presenting.

 

I would open up something like Postman and test the API request directly.

 

Eg,

 

If you run a GET request on:

https://api.hubapi.com/crm/v4/objects/deals/12345/associations/tickets

 

Where 12345 is your deal, you would get tickets associated with the deal.

 

Let's say your custom object name is Products so your object name should be something like p_products, you would do something like:

https://api.hubapi.com/crm/v4/objects/deals/12345/associations/p_products

 

Which should retrieve all the products associated with the deal.

 

0 Upvotes
BérangèreL
Community Manager
Community Manager

Associations v4 basicApi issue

SOLVE

Hi @Oldu and welcome, we are so glad to have you here!

Thanks for asking the HubSpot Community!

Here is the documentation about Custom objects.

You might want to check these resources, they might give you some ideas:

- The solution from @cowles123 on this post "Read all data from Custom Object"
- The solution from @coldrickjack on this post "API endpoint to retrieve a list of all objects in a HubSpot account"

Also, I'd love to put you in touch with our Top Experts: Hi @JBeatty, @sylvain_tirreau and @coldrickjack do you have any insights you can share with @Oldu, please?

Have a beautiful day and thanks so much for your help!
Bérangère


HubSpot’s AI-powered customer agent resolves up to 50% of customer queries instantly, with some customers reaching up to 90% resolution rates.
Learn More.


Saviez vous que la Communauté est disponible en français?
Rejoignez les discussions francophones en changeant votre langue dans les paramètres! !
0 Upvotes