Ошибка 429 при попытке пройти через Hubspot Deals API JSON
Я пытаюсь получить все предложения в моем Hubspot API в Google Sheet. Следующий скрипт Google App работал нормально, когда количество сделок было меньше 250. Теперь, когда в моем конвейере более 250 сделок, я получаю 429 ошибок, "Сервис вызван слишком много раз за один день: urlfetch." И другие ошибки,
function getDeals() {
// Prepare authentication to Hubspot
var service = getService();
var headers = {headers: {'Authorization': 'Bearer '+ service.getAccessToken()}};
// Prepare pagination
// Hubspot lets you take max 250 deals per request.
// We need to make multiple request until we get all the deals.
var keep_going = true;
var offset = 0;
var deals = Array();
while(keep_going) {
// We’ll take three properties from the deals: the source, the stage, the amount of the deal
var url = API_URL + "/deals/v1/deal/paged?&includeAssociations=true&properties=dealstage&properties=source&properties=amount&properties=dealname&properties=num_associated_contacts&limit=250&offset&properties=hubspot_owner_id&limit=250&offset="+offset;
var response = UrlFetchApp.fetch(url, headers);
var result = JSON.parse(response.getContentText());
Logger.log(result.deal)
// Are there any more results, should we stop the pagination
keep_going = result.hasMore;
offset = result.offset;
// For each deal, we take the stageId, source, amount, dealname, num_associated_contacts & hubspot_owner_id
result.deals.forEach(function(deal) {
var stageId = (deal.properties.hasOwnProperty("dealstage")) ? deal.properties.dealstage.value : "unknown";
var source = (deal.properties.hasOwnProperty("source")) ? deal.properties.source.value : "unknown";
var amount = (deal.properties.hasOwnProperty("amount")) ? deal.properties.amount.value : 0;
var dealname = (deal.properties.hasOwnProperty("dealname")) ? deal.properties.dealname.value : "unknown";
var hubspot_owner_id = (deal.properties.hasOwnProperty("hubspot_owner_id")) ? deal.properties.hubspot_owner_id.value : "unknown";
var num_associated_contacts = (deal.properties.hasOwnProperty("num_associated_contacts")) ? deal.properties.num_associated_contacts.value : "unknown";
deals.push([stageId,source,amount,dealname,num_associated_contacts,hubspot_owner_id]);
});
}
return deals;
}
2 ответа
Я думаю, что ваша проблема из множественной спецификации обоих offset
а также limit
Параметры URL в вашем url
:
"...&limit=250&offset&...&limit=250&offset=" + offset;
API HubSpot может ожидать только одно значение для определенных ключевых слов (например, limit и offset), что будет означать, что вы всегда получаете доступ только к первой странице результатов - если существует более одной страницы, вы никогда не прекратите вызывать эту функцию, пока не исчерпаете ваш UrlFetchApp
квота и скрипт завершается через необработанное исключение, как result.hasMore
всегда будет правдой.
Я бы переписал ваш скрипт для использования цикла do-while (а также для упрощения извлечения ваших свойств).
function getDeals() {
// Prepare authentication to Hubspot
const service = getService();
const fetchParams = {
headers: {'Authorization': 'Bearer '+ service.getAccessToken()}
};
// Properties to collect from each deal:
const desiredProps = [
"dealstage",
"source",
"amount",
"dealname",
"num_associated_contacts",
"hubspot_owner_id"
];
const deals = [];
// Hubspot lets you take max 250 deals per request.
// Make multiple requests until we get all the deals.
var offset = 0;
var remainingPages = 100; // just in case.
const url = API_URL + "/deals/v1/deal/paged?&includeAssociations=true&properties=dealstage&properties=source&properties=amount&properties=dealname&properties=num_associated_contacts&properties=hubspot_owner_id"
+ "&limit=250&offset=";
do {
var resp = UrlFetchApp.fetch(url + offset, fetchParams);
var result = JSON.parse(response.getContentText());
offset = result.offset;
var pageDealInfo = result.deals.map(function (deal) {
var dealInfo = desiredProperties.map(function (propName) {
var val = deal.properties[propName];
return (val === undefined ? "Unknown" : val;
});
/** add other things to dealInfo that aren't members of deal.properties
dealInfo.push(deal.<something>);
*/
return dealInfo;
});
// Add all the info for all the deals from this page of results.
if (pageDealInfo.length)
Array.prototype.push.apply(deals, pageDealInfo);
} while (result.hasMore && --remainingPages);
if (!remainingPages)
console.warn({message: "Stopped deal queries due to own page limit - more deals exist!", currentOffset: offset, gatheredDealCount: deals.length});
else
console.log({message: "Finished deal queries", totalDeals: deals.length});
return deals;
}
В соответствии с правилами использования HubSpots API:
HubSpot имеет следующие ограничения для запросов API:
10 запросов в секунду.
40000 запросов в день. Этот дневной лимит сбрасывается в полночь в соответствии с настройкой часового пояса учетной записи HubSpot.
Источник: https://developers.hubspot.com/apps/api_guidelines
Максимальный размер составляет 250 записей, которые можно получить в API сделок.
Вы должны сделать следующее
В дополнение к списку сделок каждый запрос также возвращает два значения: смещение и hasMore. Если hasMore имеет значение true, вам нужно будет сделать еще один запрос, используя смещение, чтобы получить следующую страницу записей о сделках.
offset
Параметр в следующем запросе должен быть значением, которое было возвращено в предыдущем ответе на запросы.