Sub topic 9
Creating activities through the API
This chapter assumes you can already log activities by hand and know how activities link to deals and contacts through associations. It also assumes you can read JSON and either Python or Apex. The examples use Salesforce (Apex and SOQL) and HubSpot (CRM v3 REST API with Python).
Why log through the API
Manual logging works for one rep and one call. Some logging has no person at a keyboard:
- A call-recording tool writes a summary after each call.
- A support or billing system records an event on the account.
- A migration script loads years of history from an old system.
- A product-usage trigger creates a follow-up task when a trial user invites colleagues.
In each case a program creates the same records a rep would create in the UI. The record types, required fields, and associations are the same. What changes is that you must supply every link and value yourself, because no form fills in defaults for you.
What every API-created activity needs
Whatever the CRM, a useful activity has four parts:
- A type. Task, call, note, meeting, or email.
- A date or timestamp. When it happened, or when it is due.
- A body. The outcome and the agreed next step, as in the previous chapter.
- Associations. The deal and the people involved.
If you skip associations, the API often accepts the record without complaint. The activity then exists, but it appears on no deal timeline and no report counts it. This is the most common API logging bug, and it makes the data look fine while being unusable.
Salesforce: creating a Task
In Salesforce, calls, emails, and to-dos are stored as Task records. Meetings are Event records. Two lookup fields do the linking:
WhatIdpoints to a "what" record such as an Opportunity or Account.WhoIdpoints to a "who" record, which is a Contact or Lead.
The Apex example from the topic plan creates a completed call:
Task t = new Task(
Subject = 'Discovery call with Dana Lee',
Type = 'Call',
Status = 'Completed',
ActivityDate = Date.today(),
Description = 'Confirmed budget owner. Next step: send pricing by Friday.',
WhatId = opportunityId,
WhoId = contactId
);
insert t;Four details matter here.
- Status decides where the record lives. A Task with
Status = 'Completed'appears in a deal's activity history. A Task with an open status such asNot Startedappears under open activities. The same logic applies to the next-step task. Creating it as completed hides it from a rep's to-do list. ActivityDateis a date, not a datetime. On a Task it means the due date, and for a completed call you set it to the day the call happened. It has no time zone or time of day. Events useActivityDateTimeinstead.WhoIdandWhatIdare separate on purpose. Putting an Opportunity ID inWhoIdfails, because that field accepts only Contact or Lead IDs.- Events need more fields. To create a meeting, an Event needs a start (
ActivityDateTime) and a length (DurationInMinutes) or an end (EndDateTime).
Bulk safety in Apex
Code that runs inside a trigger or batch job can receive many records at once. Insert a list, not one record per loop pass. Salesforce limits the number of DML statements per transaction, so a loop with insert inside it fails on large batches.
List<Task> tasks = new List<Task>();
for (Opportunity o : opps) {
tasks.add(new Task(
Subject = 'Send renewal quote',
Status = 'Not Started',
ActivityDate = Date.today().addDays(7),
WhatId = o.Id,
OwnerId = o.OwnerId
));
}
insert tasks;Setting OwnerId matters. Without it, the task belongs to the running user, which for an integration is a service account that nobody reads.
Salesforce from outside: the REST API
A script outside Salesforce can create the same Task by sending a POST request to the sobjects/Task endpoint. It needs an access token and your org's instance URL.
import os
import requests
instance = os.environ["SF_INSTANCE_URL"] # e.g. https://yourorg.my.salesforce.com
url = f"{instance}/services/data/v60.0/sobjects/Task"
headers = {
"Authorization": f"Bearer {os.environ['SF_ACCESS_TOKEN']}",
"Content-Type": "application/json",
}
body = {
"Subject": "Discovery call with Dana Lee",
"Status": "Completed",
"ActivityDate": "2026-11-27",
"Description": "Confirmed budget owner. Next step: send pricing by Friday.",
"WhatId": os.environ["OPPORTUNITY_ID"],
"WhoId": os.environ["CONTACT_ID"],
}
resp = requests.post(url, headers=headers, json=body, timeout=30)
resp.raise_for_status()
print(resp.json()["id"])A successful call returns the new record's ID. Field names are the API names, so the casing must match exactly.
Checking what you created
The SOQL query from the plan returns an Opportunity together with its open and completed activities. Run it after your script to confirm the links worked:
SELECT Id, Name, StageName, CloseDate,
(SELECT Subject, ActivityDate, Status FROM OpenActivities),
(SELECT Subject, ActivityDate FROM ActivityHistories)
FROM Opportunity
WHERE Id = :opportunityIdIf your Task is missing from both lists, check WhatId first. If it shows in the wrong list, check Status.
HubSpot: creating engagements with associations
In HubSpot, notes, calls, meetings, emails, and tasks are separate object types under the CRM v3 API. The pattern is the same for each: POST to /crm/v3/objects/<type> with a properties object. You can include an associations array in the same request, so the record is never unlinked.
import os
import requests
url = "https://api.hubapi.com/crm/v3/objects/notes"
headers = {
"Authorization": f"Bearer {os.environ['HUBSPOT_TOKEN']}",
"Content-Type": "application/json",
}
body = {
"properties": {
"hs_timestamp": "2026-11-27T15:00:00Z",
"hs_note_body": "Demo went well. Next step: security review on Dec 4.",
},
"associations": [
{
"to": {"id": os.environ["DEAL_ID"]},
"types": [
{"associationCategory": "HUBSPOT_DEFINED", "associationTypeId": 214}
],
}
],
}
resp = requests.post(url, headers=headers, json=body, timeout=30)
resp.raise_for_status()
print(resp.json()["id"])Points to check in this request:
hs_timestampis required and sets where the note sits on the timeline. Use ISO 8601 UTC or milliseconds since the epoch.associationTypeIdidentifies the direction and pair of objects. The value 214 means note-to-deal. A note linked to a contact uses a different ID, so copying this example for another object type gives the wrong link or an error. Look up the correct IDs in HubSpot's association documentation, or read them from the associations API for your account.- Multiple associations go in one array. To link the same note to the deal and the contact, add a second entry to
associationswith the contact's ID and the note-to-contact type ID. - Authentication uses a private app token. Give the app only the scopes it needs, such as write access to notes and to deals. Keep the token in an environment variable, as shown, and never in source code.
Creating the deal first
An activity needs a deal to attach to. If your script creates both, create the deal first, then use its returned ID in the activity request.
import os
import requests
url = "https://api.hubapi.com/crm/v3/objects/deals"
headers = {
"Authorization": f"Bearer {os.environ['HUBSPOT_TOKEN']}",
"Content-Type": "application/json",
}
body = {
"properties": {
"dealname": "Acme - Annual Platform License",
"amount": "48000",
"pipeline": "default",
"dealstage": "appointmentscheduled",
"closedate": "2026-12-31T00:00:00Z",
}
}
resp = requests.post(url, headers=headers, json=body, timeout=30)
resp.raise_for_status()
print(resp.json()["id"])The dealstage value is an internal ID, not the label you see in the UI. In the default pipeline appointmentscheduled happens to match "Appointment Scheduled". If your team has renamed or customized stages, the IDs may be different strings or numbers. Read your pipeline's stage IDs from your account before you hard-code one.
Differences at a glance
| Question | Salesforce | HubSpot |
|---|---|---|
| Object for a call or to-do | Task | Calls, Tasks (separate objects) |
| Object for a meeting | Event | Meetings |
| Deal link | `WhatId` field on the activity | Entry in `associations` with a type ID |
| Contact link | `WhoId` field on the activity | Entry in `associations` with a type ID |
| Time field | `ActivityDate` (Task), `ActivityDateTime` (Event) | `hs_timestamp` |
| Done vs. open | `Status` field | Task `hs_task_status`; other engagements are records of past events |
Writing a reliable integration
A script that works once in a test often fails in production. These habits prevent the common problems.
- Check the response every time. Use
raise_for_status()or equivalent. A script that ignores a 400 response silently drops activities. - Avoid duplicates on retry. If a request times out, you cannot tell whether the record was created. Keep an external ID, such as the call recording's ID, in the body text or a custom property. Search for it before you retry. Salesforce supports external ID fields with upsert. HubSpot's standard activity objects have no such mechanism, so a search-before-create step is the usual workaround.
- Handle rate limits. Both CRMs limit API usage. When you receive a 429 response from HubSpot, wait and retry with an increasing delay. Salesforce counts requests against a daily allowance for the org, so a runaway loop can use up capacity that other integrations need.
- Batch where possible. HubSpot offers batch create endpoints, and Salesforce offers the Composite and Bulk APIs. These use fewer requests than one call per record.
- Respect permissions. The integration user can only create what its profile or scopes allow. A 403 or "insufficient access" error usually means a missing scope or field-level permission, not a bad payload.
- Test in a sandbox. Use a Salesforce sandbox or a HubSpot developer test account before pointing a script at live deals.
Common errors
- Activity exists but is missing from the deal. The association or
WhatIdwas left out or points to the wrong record. INVALID_CROSS_REFERENCE_KEYin Salesforce. An ID inWhoIdorWhatIddoes not exist, belongs to another org, or is the wrong object type for that field.- Task shows as open when it should be done. The
Statusvalue was not a completed status in your org's picklist. - HubSpot 400 with a property error. A property name is misspelled, or an enumeration value such as a deal stage is not valid in your pipeline.
- Timeline order looks wrong. The timestamp was sent in local time without a zone, or the date was used where a datetime was expected.
Exercise
A script creates a HubSpot note with a correct body and timestamp and gets back a 201 response with an ID. A rep says the note does not appear on the deal. What is the most likely cause, and how would you fix it for the notes already created?
Show answer
The request almost certainly omitted the association, or used an association type ID that links to a different object type. HubSpot creates the note regardless, but with no link it does not show on the deal timeline. Fix the script by adding an associations entry with the deal ID and note-to-deal type ID 214. For notes already created, use the associations API to add the missing link to each note ID, rather than creating the notes again, which would produce duplicates.
Exercise
In Apex, you insert a Task with Status = 'Completed' and a valid WhatId, but you want it to appear as a to-do on the rep's list for next Tuesday. What two changes do you make?
Show answer
Set Status to an open value such as Not Started, so the Task appears under open activities, and set ActivityDate to next Tuesday's date, which is the due date. Also set OwnerId to the rep so the task appears on that rep's list rather than the integration user's.