Leads API Methods

Insert a Lead into HubSpot

POST  http://yoursite.yourportal.hubspot.com/?app=leaddirector&FormName=X

To add a lead to HubSpot via this API, simply perform an HTTP POST request to an API Form URL (you can generate these in HubSpot under Settings -> HubSpot Lead API) with some data in the body of your request.

You'll also need to make sure that the content type in your HTTP request header is "application/x-www-form-urlencoded".

Developers should note that this is an asynchronous operation. Your "add lead" request will return immediately with a confirmation (or error) message, and a conversion event GUID (see response body below). The lead, however, will not be inserted into the HubSpot system immediately. Instead, it will be placed into a queue for processing. This is done for a variety of reasons, including advanced de-duping, handling multiple near-simultaneous form submissions, ensuring fairness in processing times across customers, monitoring and metering, and more.

You can use the conversion event GUID to search for your lead later, as / if / when needed.

Required Parameters How to use Description
App ?app=leaddirector - Used in the request URL The app in HubSpot that you're posting to. This MUST remain "leaddirector", do not change this value.
Form Name &FormName=X - Used in the request URL The form name that you're posting to that you've configured in HubSpot. To configure a form, you need to login to the HubSpot portal you're creating leads in and click on "Settings -> HubSpot Lead API". Then you can follow the simple instructions to create a form in HubSpot to POST to. This will actually give you the entire URL that you need to POST to.
User Token &UserToken=X - Used in the request body The tracking cookie token value used for HubSpot lead activity tracking. You can retrieve this value from the "hubspotutk" cookie placed in the user's browser by the HubSpot JavaScript Tracking Code; the tracking code must be installed on the page that contains the form
IP Address &IPAddress=X - Used in the request body The IP Address of the lead converting. You can retrieve this from the server request.
Optional Parameters How to use Description
First Name &FirstName=X - Used in the request body The lead's first name.
Last Name &LastName=X - Used in the request body The lead's last name.
Email Address &email=X - Used in the request body The lead's email address.
Twitter Handle &TwitterHandle=X - Used in the request body The lead's Twitter handle.
Phone &phone=X - Used in the request body The lead's phone number.
Fax &Fax=X - Used in the request body The lead's fax number.
Company &Company=X - Used in the request body The lead's company name.
Address &Address=X - Used in the request body The lead's address.
Job Title &JobTitle=X - Used in the request body The lead's job title.
City &City=X - Used in the request body The lead's city.
State &State=X - Used in the request body The lead's state.
Zip Code &ZipCode=X - Used in the request body The lead's zip code.
Country &Country=X - Used in the request body The lead's country.
Message &Message=X - Used in the request body A simple message from a lead.
Website &Website=X - Used in the request body The lead's website.
Number of Employees &NumberEmployees=X - Used in the request body The number of employees at the lead's company. Numeric only (integer), e.g. 123
Annual Revenue &AnnualRevenue=X - Used in the request body The annual revenue of the lead's company. Numeric only (double), e.g. 1234.56
Close Date &CloseDate=X - Used in the request body If passed in, lead will be considered "Closed Won," and will show up as a Customer in HubSpot's Sources analytics application. MM/DD/YYYY date format only.
Any Custom Field &anyField=X - Used in the request body You can also include any custom field that you'd like in this POST, and HubSpot will include it on the lead in the Conversion Event Data.

Example URL:  http://demohubapi.app6.hubspot.com/?app=leaddirector&FormName=testform

Example POST body from the API call:

        FirstName=a&LastName=w&Email=testlead@hs.com&IPAddress=1.1.1.1&UserToken=123
    

The response from this API call includes some data about the request. Your "add lead" request will return immediately with a confirmation (or error) message, and a conversion event GUID.

Example response from the API call:

        Lead has been successfully added to HubSpot
        submissionGuid=ab44c41ffc1146829759f3b1b4eb2ac3
    

Below are examples for using the leads API in popular programming languages. All examples are intended to leave your existing form processing intact and perform a supplemental call to POST the form data to HubSpot. Some programming examples may require server or network security modifications to function correctly. We also have support for this method in certain SDK's, which you can find in the sidebar of this page.

PHP Example

        <?php
        if ($_SERVER['REQUEST_METHOD'] == "POST")
        {
        /*******************************
        your existing form processing
        ********************************/
        //START HubSpot Lead Submission
        $strPost = "";
        //create string with form POST data
        $strPost = "FirstName=" . urlencode($_POST['first_name'])
        . "&LastName=" . urlencode($_POST['last_name'])
        . "&Email=" . urlencode($_POST['email'])
        . "&TwitterHandle=" . urlencode($_POST['twitter_handle'])
        . "&Phone=" . urlencode($_POST['phone_number'])
        . "&Fax=" . urlencode($_POST['fax_number'])
        . "&Website=" . urlencode($_POST['website'])
        . "&Company=" . urlencode($_POST['company'])
        . "&JobTitle=" . urlencode($_POST['job_title'])
        . "&Address=" . urlencode($_POST['address'])
        . "&City=" . urlencode($_POST['city'])
        . "&State=" . urlencode($_POST['state'])
        . "&ZipCode=" . urlencode($_POST['zip_code'])
        . "&Country=" . urlencode($_POST['country'])
        . "&Message=" . urlencode($_POST['message'])
        . "&NumberEmployees=" . urlencode($_POST['num_employees'])
        . "&AnnualRevenue=" . urlencode($_POST['annual_revenue'])
        . "&CloseDate=" . urlencode($_POST['close_date'])
        . "&IPAddress=" . urlencode($_SERVER['REMOTE_ADDR'])
        . "&UserToken=" . urlencode($_COOKIE['hubspotutk']);
        //set POST URL
        $url = "http://yoursite.hubspot.com/?app=leaddirector&FormName=demorequest";
        //intialize cURL and send POST data
        $ch = @curl_init();
        @curl_setopt($ch, CURLOPT_POST, true);
        @curl_setopt($ch, CURLOPT_POSTFIELDS, $strPost);
        @curl_setopt($ch, CURLOPT_URL, $url);
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        @curl_exec($ch);
        @curl_close($ch);
        //END HubSpot Lead Submission
        }
        ?>
    

ASP Example

        <%
        If (Request.ServerVariables("REQUEST_METHOD") = "POST") Then
        ''''''''''''''''''''''''''''''''
        'your existing form processing
        ''''''''''''''''''''''''''''''''
        ' START HubSpot Lead Submission
        Dim strPost, xmlHttp
        'create string with POST data
        strPost = "FirstName=" & Server.URLEncode(Request.Form("first_name")) _
        & "&LastName=" & Server.URLEncode(Request.Form("last_name")) _
        & "&Email=" & Server.URLEncode(Request.Form("email")) _
        & "&TwitterHandle=" & Server.URLEncode(Request.Form("twitter_handle")) _
        & "&Phone=" & Server.URLEncode(Request.Form("phone_number")) _
        & "&Fax=" & Server.URLEncode(Request.Form("fax_number")) _
        & "&Website=" & Server.URLEncode(Request.Form("website")) _
        & "&Company=" & Server.URLEncode(Request.Form("company")) _
        & "&JobTitle=" & Server.URLEncode(Request.Form("job_title")) _
        & "&Address=" & Server.URLEncode(Request.Form("address")) _
        & "&City=" & Server.URLEncode(Request.Form("city")) _
        & "&State=" & Server.URLEncode(Request.Form("state")) _
        & "&ZipCode=" & Server.URLEncode(Request.Form("zip_code")) _
        & "&Country=" & Server.URLEncode(Request.Form("country")) _
        & "&Message=" & Server.URLEncode(Request.Form("message")) _
        & "&NumberEmployees=" & Server.URLEncode(Request.Form("num_employees")) _
        & "&AnnualRevenue=" & Server.URLEncode(Request.Form("annual_revenue")) _
        & "&CloseDate=" & Server.URLEncode(Request.Form("close_date")) _
        & "&IPAddress=" & Server.URLEncode(Request.ServerVariables("REMOTE_ADDR")) _
        & "&UserToken=" & Server.URLEncode(Request.Cookies("hubspotutk"))
        'create xmlhttp object to transmit form data
        Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
        'set method and POST destination
        xmlHttp.Open "POST", "http://yoursite.hubspot.com/?app=leaddirector&FormName=demorequest", false
        'add form encoding header
        xmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        'transmit form data
        xmlHttp.Send strPost
        'clean up
        Set xmlHttp = Nothing
        ' END HubSpot Lead Submission
        End If
        %>
    

ASP.NET Example

        void submit_Click(object sender, EventArgs e)
        {
        /********************************
        * your existing form processing
        * ******************************/
        //START HubSpot Lead Submission
        //create string with post data
        string post = "FirstName=" + Server.UrlEncode(first_name.Text)
        + "&LastName=" + Server.UrlEncode(last_name.Text)
        + "&Email=" + Server.UrlEncode(email.Text)
        + "&TwitterHandle=" + Server.UrlEncode(twitter_handle.Text)
        + "&Phone=" + Server.UrlEncode(phone_number.Text)
        + "&Fax=" + Server.UrlEncode(fax_number.Text)
        + "&Website=" + Server.UrlEncode(website.Text)
        + "&Company=" + Server.UrlEncode(company.Text)
        + "&JobTitle=" + Server.UrlEncode(job_title.Text)
        + "&Address=" + Server.UrlEncode(address.Text)
        + "&City=" + Server.UrlEncode(city.Text)
        + "&State=" + Server.UrlEncode(state.Text)
        + "&ZipCode=" + Server.UrlEncode(zip_code.Text)
        + "&Country=" + Server.UrlEncode(country.Text)
        + "&Message=" + Server.UrlEncode(message.Text)
        + "&NumberEmployees=" + Server.UrlEncode(num_employees.Text)
        + "&AnnualRevenue=" + Server.UrlEncode(annual_revenue.Text)
        + "&CloseDate=" + Server.UrlEncode(close_date.Text)
        + "&IPAddress=" + Server.UrlEncode(System.Web.HttpContext.Current.Request.UserHostAddress)
        + "&UserToken=" + Server.UrlEncode(Request.Cookies["hubspotutk"].Value);
        //set POST url
        string url = " http://yoursite.hubspot.com/?app=leaddirector&FormName=demorequest ";
        //create webrequest object and set headers for POST
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = post.Length;
        request.KeepAlive = false;
        //create streamwriter object and send data
        System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
        sw.Write(post);
        sw.Close();
        //END HubSpot Lead Submission
        }
    

Python Example

        """
         Example for posting leads to the HubSpot Lead API
        """

        import urllib
        import urllib2
        import logging

        def post_to_hubspot(url, data):
          try:
            print 'urllib2.Request(url=%r, data=%r)' % (url, urllib.urlencode(data))
            request = urllib2.Request(url=url, data=urllib.urlencode(data))
            response = urllib2.urlopen(request)
            code = response.getcode()
            print 'HubSpotLeads HTTPResponse: %r' % code
            if code not in (200, 201, 202,):
              raise Exception('HubSpotLeads failed for url=%r, data=%s, code=%s' % (url, data, code))
          except urllib2.HTTPError:
            raise Exception('HubSpotLeads failed for url=%r, data=%s' % (url, data))

        if __name__ == "__main__":

          # POST data
          data = dict(IPAddress='127.0.0.1',
            UserToken='1d6a7ac882f84764876cd998b26f12e1',
            FirstName='Adrian',
            LastName='Mott',
            Email='adrian@example.com')

          # Lead API URL
          url = 'http://..hubspot.com/?app=leaddirector&FormName=test'
          # Replace this URL with one generated in HubSpot (under "Settings -> HubSpot Lead API")

          post_to_hubspot(url, data)
    

Ruby (using the Rails framework) Example

        class HomeController < ApplicationController

         # GET /home/index
         def index
           @hubspot_url = 'yourportal.yourportalgroup.hubspot.com'
           @hubspot_path = '/?app=leaddirector&FormName=ruby+form'
           @redirect = 'http://domain.com'
           hubspot_fields = {
             :IPAddress => request.remote_ip,
             :UserToken => cookies[:hubspotutk],
             :FirstName => params[:firstName],
             :LastName  => params[:lastName],
             :Email     => params[:email]
             #:app => 'leaddirector',
             #:FormName => 'ruby form'
           }
           test = hubspot_fields.to_param
           logger.info test
           http = Net::HTTP.new(@hubspot_url)
           res = http.post(@hubspot_path, hubspot_fields.to_param)
           logger.info res.inspect
           logger.info res.body
           redirect_to @redirect
         end    
         end
    

ColdFusion Example

        <cfparam name="hubspotSuccess" default="">
        <cftry>
        <cfhttp url=" http://yoursite.hubspot.com/?app=leaddirector&FormName=demorequest " method="post"
        timeout="120" result="hubspotSuccess">
        <cfhttpparam name="FirstName" value="arguments.firstName" type=“formField”>
        <cfhttpparam name="LastName" value="arguments.lastName" type=“formField”>
        <cfhttpparam name="Email" value="arguments.emailAddress" type=“formField”>
        <cfhttpparam name="TwitterHandle" value="arguments.twitterHandle" type=“formField”>
        <cfhttpparam name="Phone" value="arguments.phoneNumber" type=“formField”>
        <cfhttpparam name="Fax" value="arguments.faxNumber" type=“formField”>
        <cfhttpparam name="Website" value="arguments.website" type=“formField”>
        <cfhttpparam name="Company" value="arguments.companyName" type=“formField”>
        <cfhttpparam name="JobTitle" value="arguments.jobTitle" type=“formField”>
        <cfhttpparam name="Address" value="arguments.address" type=“formField”>
        <cfhttpparam name="City" value="arguments.city" type=“formField”>
        <cfhttpparam name="State" value="arguments.state" type=“formField”>
        <cfhttpparam name="ZipCode" value="arguments.zipCode" type=“formField”>
        <cfhttpparam name="Country" value="arguments.country" type=“formField”>
        <cfhttpparam name="Message" value="arguments.message" type=“formField”>
        <cfhttpparam name="NumberEmployees" value="arguments.numberEmployees"
        type=“formField”>
        <cfhttpparam name="AnnualRevenue" value="arguments.annualRevenue"
        type=“formField”>
        <cfhttpparam name="CloseDate" value="arguments.closeDate" type=“formField”>
        <cfhttpparam name="IPAddress" value="#CGI.REMOTE_ADDR#" type=“formField”>
        <cfif IsDefined('cookie.hubspotutk')>
        <cfhttpparam name="UserToken" value="#cookie.hubspotutk#" type=“formField”>
        </cfif>
        </cfhttp>
        <cfcatch><cfset hubspotSuccess = 0></cfcatch>
        </cftry>