# 400 error /line\_items/search

**URL:** <https://community.hubspot.com/t/400-error-line-items-search/90207>\
**Category:** APIs & Integrations\
**Tags:** workflows, developer-tools, object, professional\
**Created:** [September 21, 2023, 6:32pm UTC](https://community.hubspot.com/t/400-error-line-items-search/90207 "2023-09-21T18:32:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ah8](https://avatars.discourse-cdn.com/v4/letter/a/ac91a4/32.png) [@ah8](https://community.hubspot.com/u/ah8)\
**Post date:** [September 21, 2023, 6:32pm UTC](https://community.hubspot.com/t/400-error-line-items-search/90207/1 "2023-09-21T18:32:17Z")

</div>

Hi,  
I am still a rather new developer, and am attempting to copy line items from a closed won deal to a pending renewal deal that was copied in a workflow from the closed won deal. I am receiving the following logs:

```lia-code-sample
INFO	[INFO] Main function initiated.
2023-09-21T17:49:30.283Z	DEBUG	[DEBUG] Extracted Deal A ID: 15122925056
2023-09-21T17:49:30.297Z	INFO	[INFO] Retrieving Deal B ID for Deal A ID: 15122925056
2023-09-21T17:49:30.297Z	DEBUG	[DEBUG] Search request to HubSpot: {"filterGroups":[{"filters":[{"propertyName":"generated_from_deal_id","operator":"EQ","value":"15122925056"}]}]}
2023-09-21T17:49:31.078Z	DEBUG	[DEBUG] Response received: {"total":1,"results":[{"id":"15123059011","properties":{"amount":"1647","closedate":"2024-10-01T00:00:00Z","createdate":"2023-09-12T13:41:36.723Z","dealname":"test delmar - auto generate - 2nd deal","dealstage":"42285693","hs_lastmodifieddate":"2023-09-19T15:59:01.152Z","hs_object_id":"15123059011","pipeline":"15984199"},"createdAt":"2023-09-12T13:41:36.723Z","updatedAt":"2023-09-19T15:59:01.152Z","archived":false}]}
2023-09-21T17:49:31.078Z	INFO	[INFO] Found Deal B with ID: 15123059011.
2023-09-21T17:49:31.116Z	INFO	[INFO] Copying line items from Deal A (ID: 15122925056) to Deal B (ID: 15123059011)
2023-09-21T17:49:31.117Z	INFO	[INFO] Retrieving line items for deal ID: 15122925056
2023-09-21T17:49:31.117Z	DEBUG	[DEBUG] API Request URL: https://api.hubapi.com/crm/v3/objects/line_items/search
2023-09-21T17:49:31.117Z	DEBUG	[DEBUG] Search Request: {"filterGroups":[{"filters":[{"propertyName":"associatedDealIds","operator":"EQ","value":"15122925056"}]}],"properties":["name","hs_sku","hs_recurring_billing_start_date","hs_recurring_billing_period","recurringbillingfrequency","quantity","price","discount","amount","hs_mrr","hs_arr","hs_tcv"],"limit":100}
2023-09-21T17:49:31.369Z	ERROR	[ERROR] HTTP error occurred while accessing retrieve line items: Request failed with status code 400
2023-09-21T17:49:31.369Z	ERROR	[ERROR] Failed to retrieve line items for deal ID: 15122925056
2023-09-21T17:49:31.369Z	ERROR	[ERROR] HTTP error occurred while accessing copy line items: Request failed with status code 400
2023-09-21T17:49:31.369Z	ERROR	[ERROR] Failed to copy line items from Deal A (ID: 15122925056) to Deal B (ID: 15123059011)
2023-09-21T17:49:31.369Z	ERROR	[ERROR] HTTP error occurred while accessing main function: Request failed with status code 400
2023-09-21T17:49:31.369Z	INFO	[INFO] Main function completed.

```

My code is as follows:

```lia-code-sample
const axios = require('axios');

const HUBSPOT_ENDPOINT = 'https://api.hubapi.com/crm/v3/objects';
const AUTHORIZATION_HEADER = {
 'Authorization': `Bearer ${process.env.billing_contacts_secret}`,
 'Content-Type': 'application/json'
};

const logger = {
 debug: (message) => console.debug(`[DEBUG] ${message}`),
 info: (message) => console.info(`[INFO] ${message}`),
 warn: (message) => console.warn(`[WARN] ${message}`),
 error: (message) => console.error(`[ERROR] ${message}`)
};

async function retrieveDealBId(dealAId) {
 try {
 logger.info(`Retrieving Deal B ID for Deal A ID: ${dealAId}`);

 // Search for Deal B with 'generated_from_deal_id' matching Deal A's ID
 const dealsSearchRequest = {
 filterGroups: [
 {
 filters: [
 {
 propertyName: 'generated_from_deal_id',
 operator: 'EQ',
 value: dealAId
 }
 ]
 }
 ]
 };

 // Log the search request before sending it
 logger.debug(`Search request to HubSpot: ${JSON.stringify(dealsSearchRequest)}`);

 const dealsResponse = await axios.post(`${HUBSPOT_ENDPOINT}/deals/search`, dealsSearchRequest, { headers: AUTHORIZATION_HEADER });
 logger.debug(`Response received: ${JSON.stringify(dealsResponse.data)}`);
 if (!dealsResponse.data.results || dealsResponse.data.results.length === 0) {
 logger.warn(`No matching Deal B found with 'generated_from_deal_id' matching Deal A's ID: ${dealAId}`);
 return null;
 }
 const dealBId = dealsResponse.data.results[0].id;
 logger.info(`Found Deal B with ID: ${dealBId}.`);
 return dealBId;
 } catch (error) {
 handleDetailedHttpError(error, 'search for deals');
 logger.error(`Failed to search for deals with generated_from_deal_id: ${dealAId}`);
 throw error;
 }
}

async function copyLineItemsFromDealAToDealB(dealAId, dealBId) {
 try {
 logger.info(`Copying line items from Deal A (ID: ${dealAId}) to Deal B (ID: ${dealBId})`);

 // Retrieve line items from Deal A
 const lineItems = await retrieveLineItems(dealAId);

 // Copy line items to Deal B
 const lineItemsEndpoint = `${HUBSPOT_ENDPOINT}/deals/${dealBId}/line_items`;

 for (const lineItem of lineItems) {
 // Store line item properties in variables
 const { properties } = lineItem;

 // Create a new line item in Deal B based on the properties of lineItem from Deal A
 const newLineItemData = {
 properties,
 // You can specify associations if needed
 };

 // Log details before making the request
 logger.debug(`Making a request to create a line item in Deal B with the following data: ${JSON.stringify(newLineItemData)}`);

 // Use axios for the request, so we can log details in case of failure
 const response = await axios.post(lineItemsEndpoint, newLineItemData, {
 headers: AUTHORIZATION_HEADER
 });

 // Log the full response
 logger.debug(`Response received: ${JSON.stringify(response.data)}`);

 logger.info(`Created line item in Deal B with ID: ${lineItem.id}`);
 }

 logger.info(`Successfully copied line items from Deal A (ID: ${dealAId}) to Deal B (ID: ${dealBId}).`);
 } catch (error) {
 handleDetailedHttpError(error, 'copy line items');
 logger.error(`Failed to copy line items from Deal A (ID: ${dealAId}) to Deal B (ID: ${dealBId})`);
 throw error;
 }
}

async function retrieveLineItems(dealId) {
 try {
 logger.info(`Retrieving line items for deal ID: ${dealId}`);

 // Construct the API request URL
 const apiURL = `${HUBSPOT_ENDPOINT}/line_items/search`;
 logger.debug(`API Request URL: ${apiURL}`);

 // Construct the search request payload with filters
 const searchRequest = {
 filterGroups: [
 {
 filters: [
 {
 propertyName: 'associatedDealIds',
 operator: 'EQ',
 value: dealId
 }
 ]
 }
 ],
 properties: [
 "name",
 "hs_sku",
 "hs_recurring_billing_start_date",
 "hs_recurring_billing_period",
 "recurringbillingfrequency",
 "quantity",
 "price",
 "discount",
 "amount",
 "hs_mrr",
 "hs_arr",
 "hs_tcv"
 // Add more properties as needed
 ],
 limit: 100, // maximum of 100
 };

 // Log the search request before making the API request
 logger.debug(`Search Request: ${JSON.stringify(searchRequest)}`);

 // Make the API request
 const response = await axios.post(apiURL, searchRequest, {
 headers: AUTHORIZATION_HEADER
 });

 // Log the full response
 logger.debug(`Response received: ${JSON.stringify(response.data)}`);

 logger.info(`Successfully retrieved line items for deal ID: ${dealId}.`);
 return response.data.results;
 } catch (error) {
 handleDetailedHttpError(error, 'retrieve line items');
 logger.error(`Failed to retrieve line items for deal ID: ${dealId}`);
 throw error;
 }
}

async function handleDetailedHttpError(error, endpoint) {
 // Handle HTTP errors here
 logger.error(`HTTP error occurred while accessing ${endpoint}: ${error.message}`);
}

exports.main = async (event, callback) => {
 logger.info("Main function initiated.");

 try {
 if (!event || !event.inputFields) {
 throw new Error("Missing inputFields in event.");
 }

 const dealAId = event.inputFields.hs_object_id;
 logger.debug(`Extracted Deal A ID: ${dealAId}`);

 if (!dealAId) {
 throw new Error("Missing Deal A ID in inputFields.");
 }

 // Retrieve Deal B's ID
 const dealBId = await retrieveDealBId(dealAId);

 if (dealBId) {
 await copyLineItemsFromDealAToDealB(dealAId, dealBId);
 }

 callback({ outputFields: {} });

 } catch (e) {
 handleDetailedHttpError(e, 'main function');
 callback({ error: e.message });
 }

 logger.info("Main function completed.");
};

```

Does anyone have any ideas what I could be doing wrong here, and how I might be able to fix it. Any help would be greatly appreciated.  
Thank you

---

<div class="post-metadata">

**Author:** ![skimura](https://avatars.discourse-cdn.com/v4/letter/s/9de053/32.png) [@skimura](https://community.hubspot.com/u/skimura)\
**Post date:** [September 22, 2023, 10:00am UTC](https://community.hubspot.com/t/400-error-line-items-search/90207/2 "2023-09-22T10:00:10Z")

</div>

@ah8

Hi.

function `retrieveLineItems`:

`propertyName: 'associatedDealIds',`

Is `associatedDealIds` means line\_item property?

If not, `search` API can search associated object by `associations.{objectType}`.

`Search for records that are associated with other specific records by using the pseudo-property associations.{objectType}.`

> **[Search the CRM - HubSpot docs](https://developers.hubspot.com/docs/api-reference/latest/crm/search-the-crm)**
>
> The CRM search endpoints make getting data more efficient by allowing developers to filter, sort, and search across any CRM object type.

How about try this?

```lia-code-sample
...
async function retrieveLineItems(dealId) {
 ...

 // Construct the search request payload with filters
 const searchRequest = {
 filterGroups: [
 {
 filters: [
 {
 // propertyName: 'associatedDealIds',
 propertyName: 'associations.deal',
 operator: 'EQ',
 value: dealId
 }
 ]
 }
 ],
...

```

Thanks.

---

<div class="post-metadata">

**Author:** ![ah8](https://avatars.discourse-cdn.com/v4/letter/a/ac91a4/32.png) [@ah8](https://community.hubspot.com/u/ah8)\
**Post date:** [September 22, 2023, 2:20pm UTC](https://community.hubspot.com/t/400-error-line-items-search/90207/3 "2023-09-22T14:20:51Z")

</div>

Thank you so much! That part is working now.
