### Marketo REST API Overview
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/getting-started
The Marketo REST API is the recommended integration point for new development. It allows interaction with core Marketo entities like Leads, Activities, Programs, and Campaigns.
```APIDOC
Marketo REST API:
Description: Provides programmatic access to Marketo Engage data and functionality.
Key Areas:
- Leads: Manage lead records, including standard and custom fields.
Reference: https://developer.adobe.com/marketo-apis/api/mapi/#tag/Leads
- Activities: Capture and manage lead interactions and events.
Reference: https://developer.adobe.com/marketo-apis/api/mapi/#tag/Activities
- Programs & Campaigns: Manage marketing programs and campaigns, including lead progression.
Reference: https://developer.adobe.com/marketo-apis/api/mapi/#tag/Campaigns
Deprecation Notice: The SOAP API is deprecated and will be unavailable after October 31st, 2025. All new development must use the REST API. Migration guides are available for existing SOAP API services.
```
--------------------------------
### Marketo JavaScript API (Lead Tracking)
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/getting-started
The Marketo JavaScript API, often referred to as Munchkin, enables lead tracking on your company's website. It captures lead behavior and interactions.
```JavaScript
// Example of Lead Tracking API usage (conceptual)
// Refer to specific documentation for exact implementation details.
// Marketo.Munchkin.init('YOUR_MUNCHKIN_ID');
// Marketo.Munchkin.track("pageView");
// Marketo.Munchkin.track("formSubmit", { field1: "value1", field2: "value2" });
// Related API: Lead Tracking
// Reference: https://developer.adobe.com/marketo-developer/marketo/javascriptapi/leadtracking/lead-tracking#lead-tracking-api
// Reference: https://developer.adobe.com/marketo-developer/marketo/javascriptapi/leadtracking/lead-tracking#munchkin-behavior
```
--------------------------------
### Get Opportunity Fields Request Example
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/lead-database/opportunities
Example GET request to retrieve opportunity field metadata, specifying a batch size.
```JSON
GET /rest/v1/opportunities/schema/fields.json?batchSize=5
```
--------------------------------
### Get Opportunity Fields Response Example
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/lead-database/opportunities
Example JSON response for retrieving metadata of multiple opportunity fields, including pagination details.
```JSON
{
"requestId": "b4a#17e995b31da",
"result": [
{
"displayName": "SFDC Oppty Id",
"name": "externalOpportunityId",
"description": null,
"dataType": "string",
"length": 50,
"isHidden": false,
"isHtmlEncodingInEmail": true,
"isSensitive": false,
"isCustom": false,
"isApiCreated": false
},
{
"displayName": "Name",
"name": "name",
"description": null,
"dataType": "string",
"length": 255,
"isHidden": false,
"isHtmlEncodingInEmail": true,
"isSensitive": false,
"isCustom": false,
"isApiCreated": false
},
{
"displayName": "Description",
"name": "description",
"description": null,
"dataType": "string",
"length": 2000,
"isHidden": false,
"isHtmlEncodingInEmail": true,
"isSensitive": false,
"isCustom": false,
"isApiCreated": false
},
{
"displayName": "Type",
"name": "type",
"description": null,
"dataType": "string",
"length": 255,
"isHidden": false,
"isHtmlEncodingInEmail": true,
"isSensitive": false,
"isCustom": false,
"isApiCreated": false
},
{
"displayName": "Stage",
"name": "stage",
"description": null,
"dataType": "string",
"length": 255,
"isHidden": false,
"isHtmlEncodingInEmail": true,
"isSensitive": false,
"isCustom": false,
"isApiCreated": false
}
],
"success": true,
"nextPageToken": "E5ZONGE4SAHALYYW6FS25KB5BM======",
"moreResult": true
}
```
--------------------------------
### Marketo Custom Objects API
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/getting-started
Manage Marketo Custom Objects, enabling one-to-many or many-to-many relationships between Marketo Leads and custom object records. Supports CRUD operations and integration with smart lists and email scripting.
```APIDOC
Marketo Custom Objects API:
Overview:
Allows for the creation of one-to-many, or many-to-many (Edge-Bridge-Edge) relationships between Marketo Leads and custom object records. Once created and published, CRUD operations can be performed via the Marketo API.
Key Functionalities:
- Create, Read, Update, Delete (CRUD) operations on custom object records.
- Integration with smart list triggers for responding to new records.
- Usage of custom object data as filters in smart lists (segmentation).
- Utilization of custom object data in emails via Email Scripting.
Related API Reference:
- [REST API - Custom Objects](https://developer.adobe.com/marketo-apis/api/mapi/#tag/Custom-Objects)
Example Use Cases:
- Storing product purchase history for leads.
- Managing event registrations for leads.
- Tracking campaign interactions beyond standard Marketo objects.
```
--------------------------------
### Marketo Get Multiple Leads (Ruby)
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/leads/getmultipleleads
Shows how to fetch multiple leads from Marketo using the Ruby Savon gem. It covers authentication setup with a signature, client configuration, and making the `getMultipleLeads` SOAP request. Requires the Savon gem and OpenSSL.
```Ruby
require 'savon' # Use version 2.0 Savon gem
require 'date'
mktowsUserId = "" # CHANGE ME
marketoSecretKey = "" # CHANGE ME
marketoSoapEndPoint = "" # CHANGE ME
marketoNameSpace = "http://www.marketo.com/mktows/"
#Create Signature
Timestamp = DateTime.now
requestTimestamp = Timestamp.to_s
encryptString = requestTimestamp + mktowsUserId
digest = OpenSSL::Digest.new('sha1')
hashedsignature = OpenSSL::HMAC.hexdigest(digest, marketoSecretKey, encryptString)
requestSignature = hashedsignature.to_s
#Create SOAP Header
headers = {
'ns1:AuthenticationHeader' => { "mktowsUserId" => mktowsUserId, "requestSignature" => requestSignature,
"requestTimestamp" => requestTimestamp
}
}
client = Savon.client(wsdl: 'http://app.marketo.com/soap/mktows/2_3?WSDL', soap_header: headers, endpoint: marketoSoapEndPoint, open_timeout: 90, read_timeout: 90, namespace_identifier: :ns1, env_namespace: 'SOAP-ENV')
#Create Request
request = {
:lead_selector => {
:key_type => "EMAIL",
:key_values => {
:string_item => ["formtest1@marketo.com", "joe@marketo.com"]
}
},
:batch_size => "100"
}
response = client.call(:get_multiple_leads, message: request)
puts response
```
--------------------------------
### Marketo getMultipleLeads XML Request Example
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/leads/getmultipleleads
An example of an XML SOAP request to the Marketo `getMultipleLeads` endpoint, demonstrating how to select leads using `LeadKeySelector` with `EMAIL` as the key type and providing a list of email addresses.
```xml
demo17_1_809934544BFABAE58E5D27146ec93f4f1e2a45f7a545f7e42e2d053c0457e72013-08-02T15:47:06-07:00EMAILformtest1@marketo.comjoe@marketo.com100
```
--------------------------------
### Marketo Bulk Lead Import cURL Example
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/bulk-import/bulk-lead-import
Demonstrates how to execute a bulk lead import request using the cURL command-line tool, including setting the multipart/form-data content type and specifying the file.
```curl
curl -i -F format=csv -F file=@lead_data.csv -F access_token=/bulk/v1/leads.json
```
--------------------------------
### Marketo REST API: Authentication and Get Leads
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/rest-api
Details how to authenticate Marketo REST API calls using an Authorization header and retrieve lead data by email. It includes examples of the required HTTP header, a sample GET request URL, and the expected JSON response format. Proper setup involves obtaining API credentials and an access token.
```APIDOC
Authorization: Bearer cdf01657-110d-4155-99a7-f986b2ff13a0:int
```
```APIDOC
/rest/v1/leads.json?&filterType=email&filterValues=
```
```JSON
{
"requestId":"c493#1511ca2b184",
"result":[
{
"id":1,
"updatedAt":"2015-08-24T20:17:23Z",
"lastName":"Elkington",
"email":"developerfeedback@marketo.com",
"createdAt":"2013-02-19T23:17:04Z",
"firstName":"Kenneth"
}
],
"success":true
}
```
--------------------------------
### Get Marketo MObjects using Java and Ruby
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/marketo-objects/getmobjects
This snippet illustrates fetching Marketo MObjects by making SOAP requests to the Marketo API. It covers authentication setup, signature generation using HMAC-SHA1, and constructing the request payload for retrieving objects based on criteria. Examples are provided for both Java and Ruby.
```Java
import com.marketo.mktows.*;
import java.net.URL;
import javax.xml.namespace.QName;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class getMObjects {
public static void main(String[] args) {
System.out.println("Executing Get MObjects");
try {
URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
String marketoUserId = "CHANGE ME";
String marketoSecretKey = "CHANGE ME";
QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
MktowsPort port = service.getMktowsApiSoapPort();
// Create Signature
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String text = df.format(new Date());
String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
String encryptString = requestTimestamp + marketoUserId ;
SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] rawHmac = mac.doFinal(encryptString.getBytes());
char[] hexChars = Hex.encodeHex(rawHmac);
String signature = new String(hexChars);
// Set Authentication Header
AuthenticationHeader header = new AuthenticationHeader();
header.setMktowsUserId(marketoUserId);
header.setRequestTimestamp(requestTimestamp);
header.setRequestSignature(signature);
// Create Request
ParamsGetMObjects request = new ParamsGetMObjects();
request.setType("Program");
MObjCriteria criteria = new MObjCriteria();
criteria.setAttrName("Id");
criteria.setComparison(ComparisonEnum.LE);
criteria.setAttrValue("1010");
MObjCriteria criteria2 = new MObjCriteria();
criteria2.setAttrName("Name");
criteria2.setComparison(ComparisonEnum.NE);
criteria2.setAttrValue("elizprogramtest");
ArrayOfMObjCriteria mObjCriteria= new ArrayOfMObjCriteria();
mObjCriteria.getMObjCriterias().add(criteria);
mObjCriteria.getMObjCriterias().add(criteria2);
request.setMObjCriteriaList(mObjCriteria);
SuccessGetMObjects result = port.getMObjects(request, header);
JAXBContext context = JAXBContext.newInstance(SuccessGetMObjects.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(result, System.out);
} catch(Exception e) {
e.printStackTrace();
}
}
}
```
```Ruby
require 'savon' # Use version 2.0 Savon gem
require 'date'
mktowsUserId = "" # CHANGE ME
marketoSecretKey = "" # CHANGE ME
marketoSoapEndPoint = "" # CHANGE ME
marketoNameSpace = "http://www.marketo.com/mktows/"
#Create Signature
Timestamp = DateTime.now
requestTimestamp = Timestamp.to_s
encryptString = requestTimestamp + mktowsUserId
digest = OpenSSL::Digest.new('sha1')
hashedsignature = OpenSSL::HMAC.hexdigest(digest, marketoSecretKey, encryptString)
requestSignature = hashedsignature.to_s
#Create SOAP Header
headers = {
'ns1:AuthenticationHeader' => { "mktowsUserId" => mktowsUserId, "requestSignature" => requestSignature,
"requestTimestamp" => requestTimestamp
}
}
client = Savon.client(wsdl: 'http://app.marketo.com/soap/mktows/2_3?WSDL', soap_header: headers, endpoint: marketoSoapEndPoint, open_timeout: 90, read_timeout: 90, namespace_identifier: :ns1, env_namespace: 'SOAP-ENV')
#Create Request
request = {
:type => "Program",
:m_obj_criteria_list => {
:m_obj_criteria => {
:attr_name => "Id",
:comparsion => "LE",
:attr_value => "1010"
},
:m_obj_criteria! => {
:attr_name => "Name",
:comparsion => "NE",
:attr_value => "elizprogramtest"
}
}
}
response = client.call(:get_m_objects, message: request)
puts response
```
--------------------------------
### Marketo Smart Campaigns API Operations
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/assets/smart-campaigns
Provides documentation for browsing and creating Marketo Smart Campaigns using the REST API. Includes details on request parameters, response structures, and usage examples.
```APIDOC
GET /rest/asset/v1/smartCampaigns.json
Description: Retrieves a list of smart campaigns, with options for filtering by update dates, folder, maximum return count, offset, and active status.
Parameters:
- earliestUpdatedAt (datetime, ISO-8601, optional): Filter by earliest update date. Must precede latestUpdatedAt if both are set.
- latestUpdatedAt (datetime, ISO-8601, optional): Filter by latest update date.
- folder (JSON object, optional): Specifies the parent folder to browse under. Format: {"id": int, "type": string}.
- maxReturn (integer, optional, default 20, max 200): Maximum number of entries to return.
- offset (integer, optional, default 0): Starting point for retrieving entries.
- isActive (boolean, optional): Filter for active Trigger campaigns.
Example Request:
GET /rest/asset/v1/smartCampaigns.json?earliestUpdatedAt=2016-09-10T23:15:00-00:00&latestUpdatedAt=2016-09-10T23:17:00-00:00
Response Structure:
{
"success": true,
"errors": [],
"requestId": "string",
"warnings": [],
"result": [
{
"id": integer,
"name": "string",
"description": "string",
"createdAt": "datetime",
"updatedAt": "datetime",
"status": "string",
"type": "string",
"isSystem": boolean,
"isActive": boolean,
"isRequestable": boolean,
"isCommunicationLimitEnabled": boolean,
"recurrence": { ... },
"qualificationRuleType": "string",
"workspace": "string",
"smartListId": integer,
"flowId": integer,
"computedUrl": "string"
}
]
}
POST /rest/asset/v1/smartCampaigns.json
Description: Creates a new smart campaign.
Request Body Format: application/x-www-form-urlencoded
Required Parameters:
- name (string): The name of the smart campaign to create.
- folder (JSON object): Specifies the parent folder where the smart campaign is created. Format: {"type": string, "id": int}.
Optional Parameters:
- description (string, max 2000 chars): A description for the smart campaign.
Example Request:
POST /rest/asset/v1/smartCampaigns.json
Content-Type: application/x-www-form-urlencoded
name=Smart Campaign 02&folder={"type": "folder","id": 640}&description=This is a smart campaign creation test.
Response Structure:
{
"success": true,
"errors": [],
"requestId": "string",
"warnings": [],
"result": [
{
"id": integer,
"name": "string",
"description": "string",
"createdAt": "datetime",
"updatedAt": "datetime",
"folder": { "id": integer, "type": "string" },
"status": "string",
"type": "string",
"isSystem": boolean,
"isActive": boolean,
"isRequestable": boolean,
"isCommunicationLimitEnabled": boolean,
"recurrence": { ... },
"qualificationRuleType": "string",
"workspace": "string",
"smartListId": integer,
"flowId": integer,
"computedUrl": "string"
}
]
}
```
--------------------------------
### Marketo requestCampaign API Documentation
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/campaigns/requestcampaign
Details the Marketo `requestCampaign` SOAP API method for running leads in Smart Campaigns. It covers parameter sets, lead identification, campaign targeting, and token management. Includes XML examples for request and response.
```APIDOC
requestCampaign:
Description: Runs an existing Marketo lead in a Marketo Smart Campaign. The Smart Campaign must have a “Campaign is Requested” trigger with Web Service API source.
Topics: SOAP, Smart Campaigns
Created For: Admin
Parameter Sets:
1. `campaignName` + `programName` + `programTokenList` (programTokenList can be empty).
2. `campaignId` alone.
Any other combination results in a bad parameter exception.
Limitations:
- Limit of 100 `leadKey` values per call. Additional keys are ignored.
Parameters:
- `leadList` (Required):
- `leadKey` (Required):
- `keyType` (Required): Specifies the field to query the lead by. Possible values: `IDNUM`, `EMAIL`, `SFDCLEADID`, `LEADOWNEREMAIL`, `SFDCACCOUNTID`, `SFDCCONTACTID`, `SFDCLEADID`, `SFDCLEADOWNERID`, `SFDCOPPTYID`.
- `keyValue` (Required): The value to query the lead by.
- `source` (Required): The campaign source. Possible values: `MKTOWS` or `SALES`.
- `campaignId` (Optional when `campaignName`, `programName`, `programTokenList` are together; otherwise Required):
- The ID of the campaign. NOTE: A bad parameter error occurs if `campaignID` and `campaignName` are both passed.
- `campaignName` (Optional when `campaignId` is present; otherwise Required in a set with `programName` and `programTokenList`):
- The name of the campaign.
- `programName` (Optional when `campaignId` is present; otherwise Required in a set with `campaignName` and `programTokenList`):
- The name of the program.
- `programTokenList` (Optional when `campaignId` is present; otherwise Required in a set with `campaignName` and `programName`):
- Array of tokens to be used in the campaign. When specifying tokens, `programName` and `campaignName` are required.
- `attrib` (Optional):
- `name` (Optional): The name of the program token (e.g., `{{my.message}}`).
- `value` (Optional): The value for the specified token name.
Request Example (XML):
```xml
demo17_1_809939944BFABAE58E5D2748397ad47b71a1439f13a51eea3137df464419792013-08-01T12:31:14-07:00MKTOWS4496EMAILlead@company.comEMAILanotherlead@company.com
```
Response Example (XML):
```xml
true
```
```
--------------------------------
### RTP Tag Setup - Marketo Javascript
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/javascriptapi/web-personalization
Provides the basic JavaScript snippet for deploying the RTP tag on a webpage. This tag is essential for enabling Marketo's Web Personalization features and must be placed in the page header.
```javascript
```
--------------------------------
### PHP getImportToListStatus Example
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/static-lists/getimporttoliststatus
Demonstrates how to use the Marketo SOAP API to check the status of an `importToList` operation using PHP. It includes setting up authentication, constructing the SOAP request, and handling the response.
```PHP
format(DATE_W3C);
$encryptString = $timeStamp . $marketoUserId;
$signature = hash_hmac('sha1', $encryptString, $marketoSecretKey);
// Create SOAP Header
$attrs = new stdClass();
$attrs->mktowsUserId = $marketoUserId;
$attrs->requestSignature = $signature;
$attrs->requestTimestamp = $timeStamp;
$authHdr = new SoapHeader($marketoNameSpace, 'AuthenticationHeader', $attrs);
$options = array("connection_timeout" => 20, "location" => $marketoSoapEndPoint);
if ($debug) {
$options["trace"] = true;
}
// Create Request
$request = new stdClass();
$request->programName = "Trav-Demo-Program";
$request->listName = "Trav-Test-List";
$params = array("paramsGetImportToListStatus" => $request);
$soapClient = new SoapClient($marketoSoapEndPoint ."?WSDL", $options);
try {
$response = $soapClient->__soapCall('getImportToListStatus', $params, $options, $authHdr);
}
catch(Exception $ex) {
var_dump($ex);
}
if ($debug) {
print "RAW request:\n" .$soapClient->__getLastRequest() ."\n";
print "RAW response:\n" .$soapClient->__getLastResponse() ."\n";
}
print_r($response);
?>
```
--------------------------------
### Marketo Bulk Lead Import File Header Example
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/bulk-import/bulk-lead-import
Illustrates the required header row for a CSV file used in Marketo's bulk lead import API, mapping column names to REST API fields.
```csv
email,firstName,lastName
test@example.com,John,Doe
```
--------------------------------
### Marketo Webhook Usage and Tips
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/webhooks/webhooks
Provides guidance on the practical application of Marketo Webhooks, including campaign context, response handling, performance considerations, and timeout limits.
```APIDOC
Webhook Usage and Tips:
- Call Webhook Flow Step: Valid only in Trigger campaigns.
- Response Updates: Updates to lead records via response mappings occur only if the web service returns a 2xx HTTP response code.
- Customization: Web services can be used for custom data enrichment, validation, or normalization.
- Performance: Webhook execution time is dependent on the external service's response time, potentially causing campaign delays. A 50ms execution time per call can accumulate significantly over many executions.
- Timeout: Marketo waits up to 30 seconds for a service call before terminating it.
- URL Encoding: Characters in the URL field are passed as written. If percent-encoding is required by the recipient server, it must be explicitly provided in the URL string.
```
--------------------------------
### Get Opportunity Field by Name Response
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/lead-database/opportunities
Example JSON response for retrieving metadata of a single opportunity field using its API name.
```JSON
{
"requestId": "12331#17e9779cb4b",
"result": [
{
"displayName": "SFDC Oppty Id",
"name": "externalOpportunityId",
"description": null,
"dataType": "string",
"length": 50,
"isHidden": false,
"isHtmlEncodingInEmail": true,
"isSensitive": false,
"isCustom": false,
"isApiCreated": false
}
],
"success": true
}
```
--------------------------------
### Marketo mergeLeads PHP Sample
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/leads/mergeleads
A PHP code sample demonstrating how to connect to the Marketo SOAP API, generate authentication headers, and execute the mergeLeads operation. It includes error handling and debugging output.
```PHP
format(DATE_W3C);
$encryptString = $timeStamp . $marketoUserId;
$signature = hash_hmac('sha1', $encryptString, $marketoSecretKey);
// Create SOAP Header
$attrs = new stdClass();
$attrs->mktowsUserId = $marketoUserId;
$attrs->requestSignature = $signature;
$attrs->requestTimestamp = $timeStamp;
$authHdr = new SoapHeader($marketoNameSpace, 'AuthenticationHeader', $attrs);
$options = array("connection_timeout" => 15, "location" => $marketoSoapEndPoint);
if ($debug) {
$options["trace"] = 1;
}
// Create Request
$keyAttrib1 = new stdClass();
$keyAttrib1->attrName = 'IDNUM';
$keyAttrib1->attrValue = '2';
$winningKeyList = new stdClass();
$winningKeyList->attribute = array($keyAttrib1);
$loser1 = new stdClass();
$loser1->attrName = "IDNUM";
$loser1->attrValue = "15";
$loser2 = new stdClass();
$loser2->attrName = "IDNUM";
$loser2->attrValue = "16";
$keyList1 = new stdClass();
$keyList1->attribute = array($loser1);
$keyList2 = new stdClass();
$keyList2->attribute = array($loser2);
$params = new stdClass();
$params->winningLeadKeyList = $winningKeyList;
$params->losingLeadKeyLists = array($keyList1, $keyList2);
$soapClient = new SoapClient($marketoSoapEndPoint ."?WSDL", $options);
try {
$leads = $soapClient->__soapCall('mergeLeads', array($params), $options, $authHdr);
// print_r($leads);
}
catch(Exception $ex) {
var_dump($ex);
}
if ($debug) {
print "RAW request:\n" .$soapClient->__getLastRequest() ."\n";
print "RAW response:\n" .$soapClient->__getLastResponse() ."\n";
}
?>
```
--------------------------------
### Create Marketo Program
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/rest/assets/programs
Creates a new program in Marketo. Requires `folder`, `name`, and `type`. Optional parameters include `description`, `costs`, and `tags`. `channel` and `type` can only be set during creation. Email programs can also include `startDate` and `endDate`.
```APIDOC
POST /rest/asset/v1/programs.json
Content-Type: application/x-www-form-urlencoded
name=API Test Program&folder={"id":1035,"type":"Folder"}&description=Sample API Program&type=Default&channel=Email Blast&costs=[{"startDate":"2015-01-01","cost":2000}]
```
```APIDOC
{
"success": true,
"warnings": [],
"errors": [],
"requestId": "d505#14d9bd96352",
"result": [
{
"id": 1207,
"name": "newProgram",
"description": "This is a test",
"createdAt": "2015-05-28T18:47:15Z+0000",
"updatedAt": "2015-05-28T18:47:15Z+0000",
"url": "https://app-devlocal1.marketo.com/#ME1207A1",
"type": "Event",
"channel": "channelOne",
"folder": {
"type": "Folder",
"value": 59,
"folderName": "blah blah"
},
"status": "",
"workspace": "Default",
"headStart": false,
"tags": null,
"costs": [
{
"startDate":"2015-01-01",
"cost":2000
}
]
}
]
}
```
--------------------------------
### Get Marketo Import Status
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/static-lists/getimporttoliststatus
Retrieve the status of an import job to a Marketo list. This example covers authentication using HMAC-SHA1 signature and making a SOAP API call. It includes implementations in both Java and Ruby.
```java
import com.marketo.mktows.*;
import java.net.URL;
import javax.xml.namespace.QName;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class GetImportToListStatus {
public static void main(String[] args) {
System.out.println("Executing Get Import To List Status");
try {
URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
String marketoUserId = "CHANGE ME";
String marketoSecretKey = "CHANGE ME";
QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
MktowsPort port = service.getMktowsApiSoapPort();
// Create Signature
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String text = df.format(new Date());
String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
String encryptString = requestTimestamp + marketoUserId ;
SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] rawHmac = mac.doFinal(encryptString.getBytes());
char[] hexChars = Hex.encodeHex(rawHmac);
String signature = new String(hexChars);
// Set Authentication Header
AuthenticationHeader header = new AuthenticationHeader();
header.setMktowsUserId(marketoUserId);
header.setRequestTimestamp(requestTimestamp);
header.setRequestSignature(signature);
// Create Request
ParamsGetImportToListStatus request = new ParamsGetImportToListStatus();
request.setProgramName("Trav-Demo-Program");
request.setListName("Trav-Test-List");
SuccessGetImportToListStatus result = port.getImportToListStatus(request, header);
JAXBContext context = JAXBContext.newInstance(SuccessGetImportToListStatus.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(result, System.out);
} catch(Exception e) {
e.printStackTrace();
}
}
}
```
```ruby
require 'savon' # Use version 2.0 Savon gem
require 'date'
mktowsUserId = "" # CHANGE ME
marketoSecretKey = "" # CHANGE ME
marketoSoapEndPoint = "" # CHANGE ME
marketoNameSpace = "http://www.marketo.com/mktows/"
#Create Signature
Timestamp = DateTime.now
requestTimestamp = Timestamp.to_s
encryptString = requestTimestamp + mktowsUserId
digest = OpenSSL::Digest.new('sha1')
hashedsignature = OpenSSL::HMAC.hexdigest(digest, marketoSecretKey, encryptString)
requestSignature = hashedsignature.to_s
#Create SOAP Header
headers = {
'ns1:AuthenticationHeader' => { "mktowsUserId" => mktowsUserId, "requestSignature" => requestSignature,
"requestTimestamp" => requestTimestamp
}
}
client = Savon.client(wsdl: 'http://app.marketo.com/soap/mktows/2_3?WSDL', soap_header: headers, endpoint: marketoSoapEndPoint, open_timeout: 90, read_timeout: 90, namespace_identifier: :ns1, env_namespace: 'SOAP-ENV')
#Create Request
request = {
:program_name => "Trav-Demo-Program",
:list_name => "Trav-Test-List"
}
response = client.call(:get_import_to_list_status, message: request)
puts response
```
--------------------------------
### Marketo Sales Persons API
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/getting-started
Manage Sales Person records and their relationships to leads in Marketo when no native CRM integration is active. This includes updating the 'externalSalesPersonId' field via the Sync Leads API.
```APIDOC
Marketo Sales Persons API:
Overview:
Enables management of Sales Person records and lead relationships in Marketo when a native CRM integration is not enabled. Sales Person records contain basic information like Name, Email, and Job Title.
Key Functionalities:
- Store basic Sales Person information (Name, Email, Job Title).
- Use Sales Person data for filtering and as tokens in Marketo.
- Manage the relationship to a sales person at the lead level via the 'externalSalesPersonId' field.
API for Updating Lead-Sales Person Relationship:
- Sync Leads API (POST /leads.json):
- Method: POST
- Endpoint: /leads.json
- Description: Used to update lead records, including setting the 'externalSalesPersonId' field to link a lead to a specific sales person.
- Parameters:
- `input`: Array of Lead objects to sync.
- `lead`: Object representing a lead.
- `externalSalesPersonId`: (Integer) The ID of the sales person to associate with the lead.
- Other lead fields as needed.
- Returns: Status of the sync operation.
Related API References:
- [REST API - Sales Persons](https://developer.adobe.com/marketo-apis/api/mapi/#tag/Sales-Persons)
- [REST API - Sync Leads](https://developer.adobe.com/marketo-apis/api/mapi/#tag/Leads/operation/syncLeadUsingPOST)
Example Use Cases:
- Assigning leads to specific sales representatives for follow-up.
- Filtering leads based on their assigned sales person.
- Personalizing communications using sales person tokens.
```
--------------------------------
### Marketo API Request Campaign Example in PHP
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/campaigns/requestcampaign
This PHP code demonstrates how to authenticate with the Marketo API and make a `requestCampaign` call. It includes setting up SOAP headers, defining request parameters for leads and campaigns, and handling responses or exceptions. Key dependencies include the `SoapClient` class and proper Marketo API credentials.
```PHP
format(DATE_W3C);
$encryptString = $timeStamp . $marketoUserId;
$signature = hash_hmac('sha1', $encryptString, $marketoSecretKey);
// Create SOAP Header
$attrs = new stdClass();
$attrs->mktowsUserId = $marketoUserId;
$attrs->requestSignature = $signature;
$attrs->requestTimestamp = $timeStamp;
$authHdr = new SoapHeader($marketoNameSpace, 'AuthenticationHeader', $attrs);
$options = array("connection_timeout" => 20, "location" => $marketoSoapEndPoint);
if ($debug) {
$options["trace"] = true;
}
// Create Request
$leadKey = array("keyType" => "EMAIL", "keyValue" => "lead@company.com");
$leadKey2 = array("keyType" => "EMAIL&qquot;, "keyValue" => "anotherlead@company.com");
$leadList = new stdClass();
$leadList->leadKey = array($leadKey, $leadKey2);
$source = "MKTOWS";
$campaignId = "4496";
$paramsRequestCampaign = new stdClass();
$paramsRequestCampaign->campaignId = $campaignId;
$paramsRequestCampaign->source = $source;
$paramsRequestCampaign->leadList = $leadList;
$params = array("paramsRequestCampaign" => $paramsRequestCampaign);
$soapClient = new SoapClient($marketoSoapEndPoint ."?WSDL", $options);
try {
$response = $soapClient->__soapCall('requestCampaign', $params, $options, $authHdr);
}
catch(Exception $ex) {
var_dump($ex);
}
if ($debug) {
print "RAW request:\n" .$soapClient->__getLastRequest() ."\n";
print "RAW response:\n" .$soapClient->__getLastResponse() ."\n";
}
print_r($response);
?>
```
--------------------------------
### Get Marketo Custom Objects (Java)
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/custom-objects/getcustomobjects
Java example demonstrating how to connect to the Marketo SOAP API, authenticate using HMAC-SHA1 signature, and retrieve custom objects. It requires the Marketo WSDL, user ID, and secret key.
```Java
import com.marketo.mktows.*;
import java.net.URL;
import javax.xml.namespace.QName;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
public class GetCustomObjects {
public static void main(String[] args) {
System.out.println("Executing Get Custom Objects");
try {
URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
String marketoUserId = "CHANGE ME";
String marketoSecretKey = "CHANGE ME";
QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
MktowsPort port = service.getMktowsApiSoapPort();
// Create Signature
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String text = df.format(new Date());
String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
String encryptString = requestTimestamp + marketoUserId ;
SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] rawHmac = mac.doFinal(encryptString.getBytes());
char[] hexChars = Hex.encodeHex(rawHmac);
String signature = new String(hexChars);
// Set Authentication Header
AuthenticationHeader header = new AuthenticationHeader();
header.setMktowsUserId(marketoUserId);
header.setRequestTimestamp(requestTimestamp);
header.setRequestSignature(signature);
// Create Request
ParamsGetCustomObjects request = new ParamsGetCustomObjects();
request.setObjTypeName("RoadShow");
ArrayOfAttribute arrayOfAttribute = new ArrayOfAttribute();
Attribute attr = new Attribute();
attr.setAttrName("MKTOID");
attr.setAttrValue("1090177");
arrayOfAttribute.getAttributes().add(attr);
JAXBElement attributes = new ObjectFactory().createParamsGetCustomObjectsCustomObjKeyList(arrayOfAttribute);
request.setCustomObjKeyList(attributes);
SuccessGetCustomObjects result = port.getCustomObjects(request, header);
JAXBContext context = JAXBContext.newInstance(SuccessGetCustomObjects.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(result, System.out);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
```
--------------------------------
### Marketo API Lead Sync (Ruby)
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/leads/synclead
Demonstrates authenticating with the Marketo SOAP API and synchronizing lead data using the Savon gem. It covers signature generation, setting up SOAP headers, and making a `sync_lead` request with lead attributes.
```Ruby
require 'savon' # Use version 2.0 Savon gem
require 'date'
mktowsUserId = "" # CHANGE ME
marketoSecretKey = "" # CHANGE ME
marketoSoapEndPoint = "" # CHANGE ME
marketoNameSpace = "http://www.marketo.com/mktows/"
#Create Signature
Timestamp = DateTime.now
requestTimestamp = Timestamp.to_s
encryptString = requestTimestamp + mktowsUserId
digest = OpenSSL::Digest.new('sha1')
hashedsignature = OpenSSL::HMAC.hexdigest(digest, marketoSecretKey, encryptString)
requestSignature = hashedsignature.to_s
#Create SOAP Header
headers = {
'ns1:AuthenticationHeader' => {
"mktowsUserId" => mktowsUserId,
"requestSignature" => requestSignature,
"requestTimestamp" => requestTimestamp
}
}
client = Savon.client(wsdl: 'http://app.marketo.com/soap/mktows/2_3?WSDL', soap_header: headers, endpoint: marketoSoapEndPoint, open_timeout: 90, read_timeout: 90, namespace_identifier: :ns1, env_namespace: 'SOAP-ENV')
#Create Request
request = {
:lead_record =>{
:Email =>"t@t.com",
:lead_attribute_list =>{
:attribute =>[
{ :attr_name => "FirstName",
:attr_value => "George" },
{ :attr_name => "LastName",
:attr_value => "of the Jungle" }
]
}
},
:return_lead =>"false"
}
response = client.call(:sync_lead, message: request)
puts response
```
--------------------------------
### Get Marketo Custom Objects (Ruby)
Source: https://experienceleague.adobe.com/en/docs/marketo-developer/marketo/home/soap/custom-objects/getcustomobjects
Ruby example using the Savon gem to connect to the Marketo SOAP API, generate an HMAC-SHA1 signature for authentication, and retrieve custom objects. It requires the Marketo WSDL, user ID, and secret key.
```Ruby
require 'savon' # Use version 2.0 Savon gem
require 'date'
mktowsUserId = "" # CHANGE ME
marketoSecretKey = "" # CHANGE ME
marketoSoapEndPoint = "" # CHANGE ME
marketoNameSpace = "http://www.marketo.com/mktows/"
#Create Signature
Timestamp = DateTime.now
requestTimestamp = Timestamp.to_s
encryptString = requestTimestamp + mktowsUserId
digest = OpenSSL::Digest.new('sha1')
hashedsignature = OpenSSL::HMAC.hexdigest(digest, marketoSecretKey, encryptString)
requestSignature = hashedsignature.to_s
#Create SOAP Header
headers = {
'ns1:AuthenticationHeader' => { "mktowsUserId" => mktowsUserId, "requestSignature" => requestSignature,
"requestTimestamp" => requestTimestamp
}
}
client = Savon.client(wsdl: 'http://app.marketo.com/soap/mktows/2_3?WSDL', soap_header: headers, endpoint: marketoSoapEndPoint, namespaces: namespaces, open_timeout: 90, read_timeout: 90, namespace_identifier: :ns1, env_namespace: 'SOAP-ENV')
#Create Request
request = {
:obj_type_name => "RoadShow",
:custom_obj_key_list => {
:attribute => {
:attr_name => "MKTOID",
:attr_value => "1090177" }
},
:"include_attributes/" => ""
}
response = client.call(:get_custom_objects, message: request)
puts response
```