Working with Marketo Rest API

Python is an excellent tool for calling Marketo Rest API.

Get Access Token


import requests

def authenticate(host):
    headers = {'Accept-Encoding': 'gzip'}
    args = {
        'grant_type': 'client_credentials',
        'client_id': 'client_id',
        'client_secret': 'client_secret'
    }
    
    path = "/identity/oauth/token"

    resp = requests.post(host + path, headers=headers, params=args)
    data = resp.json()
    if data is None: raise Exception("Empty Response")
    if 'error' in data:
        if data['error'] in ['unauthorized', 'invalid_client']:
            raise Exception(data['error_description'])
            
    return data['access_token']

    
host = "https://XXX-XXX-XXX.mktorest.com"

access_token = authenticate(host)
print (access_token)


Creating a bulk import Job

To make a bulk import request, you need to set your content-type header to “multipart/form-data” and include at least a file parameter with your file content, and a format parameter with the value “csv”, “tsv”, or “ssv” denoting your file format.



listId = '1120'

filename = 'Lead Customer.csv'
filepath = 'C:/Python/Data/' + filename

endpoint = "/bulk/v1/leads.json"

headers = {'Content-type': 'multipart/form-data'}

args = {
    'access_token': access_token,
    'format': 'csv',
	'listId': listId,
	'lookupField' : 'ID'
}

with open(filepath, 'rb') as oFile:
    files = {'file': (filename, oFile, 'text/plain')}
    resp = requests.post(host + endpoint, params=args, files=files)
    print(resp.headers)
    print(resp.json())