TABLE OF CONTENTS



Cheat Sheet


Web Methods


Important note:


These methods require the use of an API token set in a cookie. Please check the section on authentication! 



Bulk loading of leads



Method Function 



URL 



Method 



Version 



Import a CSV file(s)



ImportCsvFiles



POST multi part form



2.6.0.1




Individual Lead Management Methods


These are RESTful requests formatted in the style of


Entity/Id/action


OR


Entity/Id?param1=x&param2=y



Method Function 



URL 



Params 



Method 



Version 



Deactivate a Lead



DeactivateLeadByPhone



/{phoneNumber}?Scope={scope}&li stID={listId}



DELETE



2.6.0.1



Deactivate a Lead



DeactivateLeadByRefId



/{referenceId}?Scope={scope}&listI


D={listId}



DELETE



2.8.0



Deactivate a Lead



DeactivateLeadId



/leadId



DELETE



2.6.0.1



Add lead Number to Do Not Call



DncLeadPhoneNumber



/{phoneNumber}?listID={listId}&dn ccategories={categoryIds}



POST



2.6.0.1



Add lead Id Number to Do Not Call



DncLeadId



/leadId



POST



2.6.5.0



Add a new Lead



AddLead



Post Request



POST



2.8.5



Bring lead back



ReactivateLeadByPhone



/{phoneNumber}?listID={listId}&reactivateDnc={reactivateDnc}



POST



2.8.0



Bring lead back



ReactivateLeadByLeadId



/{leadId}&reactivateDnc={reactivateDnc}



POST



2.8.0



Bring lead back



ReactivateLeadByLeadByRefId



/{referenceId}?listID={listId}&reactivateDnc={reactivateDnc}



POST



2.8.0



Move/update lead



MoveLeadByRefId



{phoneNumber}?newListID={newLis tId}&oldListID={oldListId}&resetAtte mpts={resetAttempts}&updateFinal ={updateFinal}&finalCode={finalCod e}



POST



2.8.5



Full Process


  1. Authenticate and get an API token
  2. Call relevant API requests
  3. Process return result


Notes


  • If you require secondary table information (scripting information) please use the Bulk Loader not “AddLead”
  • The bulk loader does not require you write a CSV file to disk, only that you stream your leads to the server
  • You need to have a phone number when adding a lead.
  • If you use “hot leads” or otherwise have leads you would like to push as high priority, you can set this IsHighPriority property on the LeadPhone object. This will prioritise the lead to be called above all others, scheduling it for an almost immediate call
  • The maximum allowed request size is 51200000 bytes, or 51.2MB. Please consider this when sending large CSV files with the bulk import method. A request with too large a payload will return a HTTP 413 status code.

What is a RESTful API


A RESTful API is an API that communicates over Hypertext Transfer Protocol to retrieve data and to send data to remote servers using the same HTTP Verbs as the Web.


See https://en.wikipedia.org/wiki/Representational_state_transfer for more information 




Authentication


Tokens API


All API methods require a security token to use the system. This token is stored in the HTTP cookie to allow multiple API calls from one authentication request.


A token is requested by authenticating with a user password combination. The Token service API will return a token on success.


Token URL

https://[CUSTOMER].maxcontact.com/webservices/services/apitoken/login/{login}


 

Password

The password needs to be sent in the authorization header of the request; the password needs to be converted to Base64 with ASCII encoding to get the bytes[] from the password string. 


 

Permissions

The user account needs to be in a permission role that has the ‘API Token Access’ permission enabled on MaxContact


Steps:


  1. Make a request to the token Uri
  2. Store token key for any subsequent requests
  3. Make request to the Lead Management Service


Recommendations


  • It is recommended that you keep track of the Token Key and its expiry as making a request every time can slow down the import process.
  • Login should be plain text 
  • To achieve the response in the same format as the request, it is required that the ‘Accept’ header is included


 

When a successful API call is made to the API Token service, it will return a json/xml object structured as below.


To be removed - By default, the server will return this object as XML unless you specify a content type of json


Example default return


<APIToken xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">


<ID>123</ID>


<UserID>1</UserID>


<IsApplicationToken>false</IsApplicationToken>


<TokenKey>e59de8c5-141e-46fa-9d06-1222ae328c50-08122015125030</TokenKey>


<ExpiryDate>2018-01-01T00:00:00.0000000+00:00</ExpiryDate>


<UserName>LAB</UserName>


<UserAddress>LAB</UserAddress>


</APIToken>


The TokenKey property is the API key you should use for the remainder of the session. You can use the ExpiryDate property to see when this will expire.


Lead Management API Return Object


Every API call returns an object “ImportDataResult” to notify of any issues or a success failure. This will contain a Boolean flag to represent if the request was successful and a collection of errors and their severity.


In some cases, such as bulk loading data you may also receive information such as Immediate Rejected Records and the Import ID which can be used as your reference for any future callbacks.


The server will return this object as XML.


<LeadAPIResult.ImportDataResult xmlns="http://schemas.datacontract.org/2004/07/Max.LeadManagement.LeadAPIPublic" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">


<Errors xmlns:a="http://schemas.datacontract.org/2004/07/Max.LeadManagement.APIError">


<a:APIError>


<a:ErrorCode>NotAuth</a:ErrorCode>


<a:ErrorSeverity>Severe</a:ErrorSeverity>


<a:ErrorText>You are not authorised to use this service</a:ErrorText>


</a:APIError>


</Errors>


<ImmediateRejectCount>0</ImmediateRejectCount>


<ImportIDs i:nil="true" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>


<Success>false</Success>


</LeadAPIResult.ImportDataResult>


Bulk loading leads


To use the bulk loading API leads, you are required to use a multipart FORM POST containing an octet stream, please ensure you are fully aware of this method for HTTP Transport



Creating an Import Mapping


Import mappings need to be created before the bulk loading of leads will work. To do this you will need to access the Manager Portal and go to the following URL:


https://[CUSTOMER].maxcontact.com/ManagerPortal/ImportMapper


In the mapping you can specify key details of the import such as the list to import into, the priority of the import, deduplication and do not call checking along with mappings of which CSV columns map to which Max Contact database columns.


Attaching the file to import


The CSV file to be uploaded can have any columns as required. A separate mapper page can be found in the MaxContact management portal to assign these custom columns to the correct MaxContact data columns. Please contact your MaxContact installer to arrange mapping.


Example CSV format 


phone,id,first_name,last_name


“07777123456”,1,“Bob”,”Smith”


Options


It is possible to control some of the action of the import using an options parameter in the header. This should be a Json object containing the settings.


  • Some options may be ignored if the master configuration of the import is set to do so, such as ListID when an import is done to an already specified list

 URLs


The following URL can be used to make requests to Max Contact to do bulk lead imports


https://[CUSTOMER].maxcontact.com/webservices/services/LeadManagement/ImportCsvFiles


Headers


The Following headers need to be added to your request


Content-Type: multipart/form-data; boundary=[YOUR DELIMITER]

Cookie: TokenKey=[YOUR TOKEN]



Mandatory Params


“filename” 


In the multipart section for the octet/stream it is required that a filename is in place. 


Filename=somefilename.csv


 


“Mapname” 


A mapname is the name of the template you are going to be using to map the data into the import system. For each lead supplier, a different template can be supplied in the options


Add this key to the multi part content


mapname=template1

 


Example Multipart Content



 --DELIMITER


Content-Disposition: form-data; name="CSV Upload"; filename="filename.csv


Content-Type: application/octet-stream


 

first_name,last_name,CrmID,mobile,home,work


“John","Smith","abc-123","9876543210","9876543210","9876543210


“Joe","Smith","def-456","9876543210","9876543210","9876543210


“Jack","Smith","ghi-789","9876543210","9876543210","9876543210


 

--DELIMITER


Content-Type: text/plain; charset=utf-8


Content-Disposition: form-data; name="mapname"


 

My Mapping


--DELIMITER


Content-Type: text/plain; charset=utf-8


Content-Disposition: form-data; name="options"


 

[JSON Optional Parameters]}


--DELIMITER--



Optional Params



Field



Type



ListId



Integer



SecondaryEnabled



Boolean



CheckDnc



Boolean



Dedupe



Boolean



RemoveNonDigits



Boolean



TruncateExtraDigits



Boolean




Response When Bulk Imports Complete


To receive a HTTP POST response when an import has failed or completed a Response URL must be provided when setting up the Import API Mapping. For example, the Response URL may be something like


https://api.yourcompany.com/importresponse


When the import completes Max Contact will make a request to the supplied URL with an “ImportDataResponse” object which will detail which rows have been rejected and the reasons why. Below is an XML example of what you will receive. This can easily be reference for detribalisation using the LeadAPIPublic library.



<LeadAPIResult.ImportDataResponse xmlns="http://schemas.datacontract.org/2004/07/Max.LeadManagement.LeadAPIPublic" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">


<Errors xmlns:a="http://schemas.datacontract.org/2004/07/Max.LeadManagement.APIError">


<a:APIError>


<a:ErrorCode>GeneralInfo</a:ErrorCode>


<a:ErrorSeverity>Info</a:ErrorSeverity>


<a:ErrorText>Line: 1 Reason: Duplicate</a:ErrorText>


</a:APIError>


<a:APIError>


<a:ErrorCode>GeneralInfo</a:ErrorCode>


<a:ErrorSeverity>Info</a:ErrorSeverity>


<a:ErrorText>Line: 2 Reason: DoNotCall</a:ErrorText>


</a:APIError>


<a:APIError>


<a:ErrorCode>GeneralInfo</a:ErrorCode>


<a:ErrorSeverity>Info</a:ErrorSeverity>


<a:ErrorText>Line: 3 Reason: DuplicateInFile</a:ErrorText>


</a:APIError>


<a:APIError>


<a:ErrorCode>GeneralInfo</a:ErrorCode>


<a:ErrorSeverity>Info</a:ErrorSeverity>


<a:ErrorText>Line: 4 Reason: InvalidSourceFormat</a:ErrorText>


</a:APIError>


<a:APIError>


<a:ErrorCode>GeneralInfo</a:ErrorCode>


<a:ErrorSeverity>Info</a:ErrorSeverity>


<a:ErrorText>Line: 5 Reason: InvalidPhoneNumber</a:ErrorText>


</a:APIError>


</Errors>


<ImmediateRejectCount>0</ImmediateRejectCount>


<ImportIDs i:nil="true" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>


<LeadsImported>100</ LeadsImported >


<RejectedDedupe>1</ RejectedDedupe>


<RejectedDedupeFile>1</ RejectedDedupeFile>


<RejectedDnc>1</ RejectedDnc>


<RejectedParsing>1</ RejectedParsing>


<RejectedValidation>1</ RejectedValidation >


<Success>false</Success>


</LeadAPIResult.ImportDataResponse >


You will be able to configure the response format to be either XML or JSON depending on the configuration on the Import API Mapping page in Manager Portal.


https://[CUSTOMER].maxcontact.com/ManagerPortal/ImportMapper



Lead Management API


Deactivate Lead By Phone

Finds leads by their Phone Number and makes them ineligible for dialling


DELETE - LeadManagement/DeactivateLeadByPhone/{phoneNumber:string}?

Query String Params –

Scope={scope: DeActivationScope}

ListID={listId:integer}

ResultCode={resultCode:string}

UpdateHistory={update:boolean}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/DeactivateLeadByPhone/07811223123?Scope=0&listID=123&ResultCode=TEST&UpdateHistory=false 


( * = optional)



Param 



Description 





Default 



PhoneNumber



The given Phone to kill



F



N/A



Scope



Given a phone number, decide while lead to deactivate. You can kill all leads, the oldest leads or certain time based leads.


This is useful for deduplication and pruning


 


    All = 0,


    KeepNewest = 1,


    Over6mOld = 2,


    Over12mOld = 3



T



0 (All)



ListId



The list to remove the duplicate from. If this is set to 0, it will apply to all lists



T



0 (All)



ResultCode



The result code you want to use when deactivating the lead



T



“API-


Removed”



UpdateHistory



Go and find the last entry in History and change the result code to the specified.



T



False




Deactivate Lead Id


Finds a lead by ID and makes it ineligible for dialling


DELETE - LeadManagement/DeactivateLeadId/{leadId:string}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/DeactivateLeadId/1



Deactivate Lead By Ref Id


Finds leads by their reference ID from the lead table and makes them ineligible for dialling


DELETE - LeadManagement/DeactivateLeadByRefId/{referenceId:string}?

Query String Params –

Scope={scope: DeActivationScope}

ListID={listId:integer}

ResultCode={resultCode:string}

UpdateHistory={update:boolean}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/DeactivateLeadByRefId/CUSTREF123ABC?Scope=0&listID=123&ResultCode=TEST&UpdateHistory=false 


( * = optional)



Param 



Description 





Default 



ReferenceId



The reference Id in the database as imported



F



N/A



Scope



Given a phone number, decide while lead to deactivate. You can kill all leads, the oldest leads or certain time based leads.


This is useful for deduplication and pruning


 


    All = 0,


    KeepNewest = 1,


    Over6mOld = 2,


    Over12mOld = 3



T



0 (All)



ListId



The list to remove the duplicate from. If this is set to 0, it will apply to all lists



T



0 (All)



ResultCode



The result code you want to use when deactivating the lead



T



“API-


Removed”



UpdateHistory



Go and find the last entry in History and change the result code to the specified.



T



False




Deactivate Leads By Ref Id


Finds leads by their reference ID from the lead table and makes them ineligible for dialling


POST - LeadManagement/DeactivateLeadsByRefId

Query String Params –

Scope={scope: DeActivationScope}

ListID={listId:integer}

ResultCode={resultCode:string}

UpdateHistory={update:boolean}

Request body – string[]


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/DeactivateLeadsByRefId?Scope=0&listID=123&ResultCode=TEST&UpdateHistory=false 


Content-Disposition: form-data; name="referenceIds"


Content Body:

 [“abc-123”,

“def-456”,

“ghi-789”]


( * = optional)



Param 



Description 





Default 



ReferenceId



The reference Id in the database as imported



F



N/A



Scope



Given a phone number, decide while lead to deactivate. You can kill all leads, the oldest leads or certain time based leads.


This is useful for deduplication and pruning


 


    All = 0,


    KeepNewest = 1,


    Over6mOld = 2,


    Over12mOld = 3



T



0 (All)



ListId



The list to remove the duplicate from. If this is set to 0, it will apply to all lists



T



0 (All)



ResultCode



The result code you want to use when deactivating the lead



T



“API-


Removed”



UpdateHistory



Go and find the last entry in History and change the result code to the specified.



T



False




Dnc Lead Phone Number - Can’t be done in the product currently!


Add a lead to the Do Not Call register by its phone number, list Id and Do Not Call category


POST - LeadManagement/DncLeadPhoneNumber/{phoneNumber:string}

Query String Params –

ListID={listId:integer}

DncCategories={dncCategories:string}


Example:


/LeadManagement/DncLeadPhoneNumber/07811223123?listID=1&dnccategories=1,2,3 


( * = optional)



Param 



Description 





Default 



PhoneNumber



The given Phone to kill



F



N/A



ListId



The list to add the Dnc to. If this is set to 0, it will apply to all lists



T



0 (All)



Dnccategories



This is a list of the Id of the category to remove the Do Not


Calls from. This will be supplied by the customer or MaxContactNow



F



N/A



Add Lead


NOTE: This will only add a lead, this method will NOT add any secondary data into the database. If you require secondary mappings i.e. for scripting, please use the ImportCsvFiles or ImportXmlFiles methods. Phone numbers must also be validated prior to the AddLead endpoint being called.


POST - LeadManagement/AddLead

Request body - APILead


Example:

https://(customer).maxcontact.com/webservices/services/LeadManagement/AddLead


Content Body:



 "Name": "Mr",

 "Name2": "Smith",

 "OtherInfo": "Mr Smith",

 "REF": "123456",

 "ReferenceID": "123436",

 "Supplier": "LeadSupplier ABC",

 "ListID": 2,

 "Cost": 2.6,

 "LeadPhones": [  

       {

              "PhoneNum": "07989137439",  

              "PhoneTypeID": 0,   

              "TimeZoneID": 0,   

              "IsHighPriority": true

       },

       {  

              “PhoneNum": "07741848903",

              "PhoneTypeID": 1,

              "TimeZoneID": 0

       } ]

}

Max provide a structured class of APILead and APILeadPhone. If you are not using C# class examples, you will need to pass a structured JSON with your request.



Lead Fields 



Field Name 



Type 



Comments 



Name



String



For future/reference use



Name2



String



For future/reference use



OtherInfo



String



Info displayed to the agent (required) 



ReferenceID



String



The reference number for this lead



Supplier



String



The lead’s supplier (you)



ListID



Int



The ID of the list for the lead to go into. Please ask Max Contact for this.



Cost



decimal



Price of the lead (optional, set to 0)




Lead Phone Fields 



Field Name 



Type 



Comments 



CanCallDate



DateTime



Date and time to place the call to this number. Set to DateTime.Now for default behaviour



PhoneNum



String



The phone number to call



PhoneTypeID



Integer



The type of the number


0  = Home


1  = Work


2  = Mobile



TimeZoneID



Integer



Set to 0 unless specified by Max Contact



IsHighPriority



Boolean



Setting to true will cause MaxContact to immediately dial this lead instead of using the usual dialling priority order



Reactivate Lead By Phone


Make a lead eligible to dial by phone number


POST - LeadManagement/ReactivateLeadByPhone/{phoneNumber:string}?

Query String Params –

ListID={listId:integer}

ReactivateDNC={reactivateDnc:boolean}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/ReactivateLeadByPhone/01234567890?listID=123&reactivateDnc=false


( * = optional)



Param



Description



*



Default



PhoneNumber



The given Phone to kill



F



N/A



ListId



The list to remove the duplicate from. If this is set to 0, it will apply to all lists



T



0 (All)



ReactivateDNC



This will reactivate any leads whose final code is a DNC



T



False



Reactivate Lead Id


Make a lead eligible to dial by lead id


POST - LeadManagement/ReactivateLeadId/{leadid:string}?

Query String Params –

ReactivateDNC={reactivateDnc:boolean}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/ReactivateLeadId/1234?reactivateDnc=false



Param



Description



*



Default



LeadId



The given Phone to bring back



F



N/A



ReactivateDNC



This will reactivate the lead if the final code is a DNC



T



False



Reactivate Lead By Ref Id


Make a lead eligible to dial by its reference id imported to the lead table


POST - LeadManagement/ReactivateLeadByRefId/{referenceid:string}?

Query String Params –

ListID={listId:integer}

ReactivateDNC={reactivateDnc:boolean}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/ReactivateLeadByRefId/abc-123?listID=123&reactivateDnc=false


( * = optional)



Param



Description



*



Default



ReferenceId



The reference Id in the database as imported



F



N/A



ListId



The list to remove the duplicate from. If this is set to 0, it will apply to all lists



T



0 (All)



ReactivateDNC



This will reactivate the lead if the final code is a DNC



T



False



Reactivate Leads By Ref Ids


Make leads eligible to dial by their reference id imported to the lead table


POST - LeadManagement/ReactivateLeadByRefIds/?

Query String Params –

ReactivateDNC={reactivateDnc:boolean}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/ReactivateLeadByRefIds?listID=123&reactivateDnc=false



Content-Disposition: form-data; name="referenceIds"


Content Body:


 [“abc-123”,

“def-456”,

“ghi-789”]



Param



Description



*



Default



ReactivateDNC



This will reactivate the lead if the final code is a DNC



T



False




Move Lead By Ref Id


Moves lead to a new list by its reference id imported into the lead table


POST - LeadManagement/MoveLeadByRefId/{referenceId:string}?

Query String Params –

NewListID={newListId:integer}

OldListID={oldListId:integer}

ResetAttempts={resetAttempts:boolean}

UpdateFinal={updateFinal:boolean}

FinalCode={finalCode:integer}


Example:


https://(customer).maxcontact.com/webservices/services/LeadManagement/MoveLeadByRefId/ABC123456?newListID=2&oldListID=1&res etAttempts=false&updateFinal=false&finalCode=0



Move Lead By Phone

Moves lead to a new list by it’s phone number


NOTE: This will move all leads that have the same phone number.


POST - LeadManagement/MoveLeadByPhone/{phoneNumber:string}?

Query String Params –

NewListID={newListId:integer}

OldListID={oldListId:integer}

ResetAttempts={resetAttempts:boolean}

UpdateFinal={updateFinal:boolean}

FinalCode={finalCode:integer}


Example:

https://(customer).maxcontact.com/webservices/services/LeadManagement/MoveLeadByPhone/(phone number)?newListID=2&oldListID=1&resetAttempts=false&updateFinal=false&finalCode=0


( * = optional)



Param



Type 



Description



*



Default



phoneNumber/ referenceId



String



The given Phone or reference Id to search for



F



N/A



newListID



Int



The List ID to change to



T



0 = ignore



oldListID



Int



The List ID to search in (0 for global search)



T



0 = all



resetAttempts



Bool



True to reset to 0 attempts



T



False



updateFinal



Bool



True to update final attempts



T



False



finalCode



Int



The code to use when changing final status



T



0




Final Codes 


In order to change a lead’s final status, i.e. to make it inactive or reactivate it, you need to:-


updateFinal = true


finalCode = chosen code



Final Code Values 



Code ID 



Code Status 



0



Eligible to dial, i.e. active



1



Final Result. i.e. Inactive



2



Set as a Do Not Call



Errors and Error Handling


Token Errors

A null or undefined token is a sign of an error, any HTTP Response Codes other than 200 OK is also a sign of an error


Import API Errors

When a Lead API action is called, it will return an object of “ImportDataResult” (in either XML or JSON depending on your request options).

This class contains an overview of the success of the request, and any other useful information.

For example, an Import request will return an ImportDataResult with a number of ImmediateRejectCounts. The error array will contain detail of the issue causing immediate rejects of a lead.


Object Definitions

Error IDs



Error ID



Error Value



NotAuth



0



GeneralInfo



1



GeneralWarning



2



GeneralError



3



FileMissing



4



FileTooLarge



5



FileWriteError



6



CommsError



7



DBError



8



NoMapMatch



9



NoMapFound         



10



InvalidLead



11



InvalidLeadId



12



PhoneNumberNotFound



13



Error Severities



Error Severity



Severity Value



None



0



Info



1



Warning



2



Severe



3



 

An API error is a list of errors that occurred during the lead API process. For example, it may return the following:



    ErrorId = ErrorID.NoMapMatch, 

    ErrorText = "You do not have a valid map to import with", 

    ErrorSeverity = ErrorSeverities.Severe 

}

or



    ErrorId = ErrorID.GeneralWarning, 

    ErrorText = "There were a high number of rejected leads", 

    ErrorSeverity = ErrorSeverities.Warning 

}


Example Code

Get Token Example Code

Here is an example of how to create an authentication token for future API requests.

var targetUri = new Uri("https://[CUSTOMER].maxcontact.com/webservices/services/apitoken/login/{login}"); 

using (var httpClient = new HttpClient())

{

// Set buffer to a 10 megs for receiving large data sets        

httpClient.MaxResponseContentBufferSize = 10000000;

var base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(password));        

httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64);

using (HttpResponseMessage response = await httpClient.GetAsync(targetUri))

using (HttpContent content = response.Content)

{

string httpResult = await content.ReadAsStringAsync();            

                if (httpResult.Length > 0)

                {

                        var token = (APIToken)Helper.XmlToObject(httpResult, typeof(APIToken));

                        return token;

                } 

        }      

}


Setting Token Example Code

var cookies = new CookieContainer(); cookies.Add(host, new Cookie("TokenKey", returnedToken.TokenKey));

var handler = new HttpClientHandler() { CookieContainer = cookies }) 


Bulk Load Leads

Here is a sample of using the API Lead service in C# to bulk import Leads

Uri uri = new Uri("https://[CUSTOMER].maxcontact.com........")
FileInfo fi = new FileInfo(“[PATH TO YOUR FILE]”);       
string fileName = fi.Name;       
byte[] fileContents = File.ReadAllBytes(fi.FullName);


// open an HttpRequest object
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, uri);       
message.Headers.ExpectContinue = false;

// Fill out the cookie with the token obtained during auth       
CookieContainer cookies = new CookieContainer();       
cookies.Add(uri, new Cookie("TokenKey", "[YOUR TOKEN KEY]"));

// Create a new multipart content section
MultipartFormDataContent multiPartContent = new MultipartFormDataContent("--Max Test-");
ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);

// Its a stream!
byteArrayContent.Headers.Add("Content-Type", "application/octet-stream");       
multiPartContent.Add(byteArrayContent, "Test CSV Upload", fileName);

// These are all of the options for the server to process       
var formData = new[] {

                   // REQUIRED
                   new KeyValuePair<string, string>("mapname", "default"),
                   // any optional options here in Json
                   //new KeyValuePair<string, string>("options", "{ ListID: 1 }"), 
};

// Add the form fields to the request       
foreach (var kpv in formData)            
multiPartContent.Add(new StringContent(kpv.Value), kpv.Key);

message.Content = multiPartContent;

// Make the request
using (var handler = new HttpClientHandler() { CookieContainer = cookies })       
using (var client = new HttpClient(handler))
{           

       var httpRequest = client.SendAsync(message, HttpCompletionOption.ResponseContentRead);
       HttpResponseMessage httpResponse = httpRequest.Result;
       HttpStatusCode statusCode = httpResponse.StatusCode;
       HttpContent responseContent = httpResponse.Content;

       if (responseContent != null)
              var stringContentsTask = responseContent.ReadAsString();             
}