More articles

How To "Get" Companies From HubSpot Using C#

Written by
Filed under
Published on
Modified on

I haven't used too many CRM platforms in the past, but for sure HubSpot's features are plentiful for the small business person on the go. And if you're looking to integrate your own data with HubSpot, they also offer a free (though rate limited) RESTful API, of which I will be covering today.

RESTful API

Hubspot offers a very robust API for their CRM platform and you can handle everything from company and contact creation to handling deals and calendar events. Today I will only be covering the Company features of the API. However the same methods can be used across the board for each and every type of request. The only thing that changes is the URL which you will be making requests to. But before you can get started, you'll need to get your HAPIKey from Hubspot.

Get Your HAPIKey

Hubspot CRM Integration With C#

Before you can do anything with the API, you will need to get your HAPIKey from Hubspot. To get to its location, head on over to the top right dropdown bar that appears on every page and head to the Integrations section of HubSpot.

Hubspot CRM Integration With C#

Your HubSpot API key will be sitting right there waiting for you. Do not share your key with anyone. Because API requests are rate limited, anyone using your token will be using up your quota. Each and every request will require you pass in this token as a parameter going forward.

Get a company

This is perfect for keeping your contact data synced with Hubspot. Each contact in Hubspot has an internal ID, which you can use to externally map to. This ID will be how you will retrieve Companies from the API. I chose to create a syncing database tables that maps the HubSpot ID with my own internal ID for faster lookup.

Company URL: https://api.hubapi.com/companies/v2/companies/companyid?hapikey=demo

The following function makes use of the WebRequest class in .NET, which does exactly that. It makes an HTTP request, either GET or POST, with the given request parameters and it returns a WebResponse.


private void GetCompany(string id)
{
    string url = "https://api.hubapi.com/companies/v2/companies/" + id + "?hapikey=your hapikey goes here";

    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "GET";

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        Response.Write("Response: " + result);
    }
}

If your request is valid, you will receive a JSON response, as a string of course. If invalid however, you will receive a 404. HubSpot will only return the data fields that are set for your Company. If for example, you are missing the address, it will not be a part of the response.

Get all Companies

Retrieving all companies is a bit more work, as HubSpot will only return a maximum of 250 entries per request, which means we will have to paginate through the requests. Lucky for us, HubSpot gives us a few helpful features to aid in that process, such as a has-more parameter and an offset parameter which we can pass in to continue on with the next page of data.

Essentially, if "has-more", than you will need to make another request with the given "offset". Until "has-more" returns False. A "do-while" loop will take care of that condition for us.


    private void GetAllHubspotCompanies()
    {
        var counter = 0;
        string offset = string.Empty;
        bool hasmore = false;
        var hapikey = "your api key goes here";

        do
        {
            string url = string.Format("https://api.hubapi.com/companies/v2/companies/paged?hapikey={0}&properties=name&properties=website&properties=address&limit=2{1}", hapikey, offset);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();

                JObject jObject = JObject.Parse(result);
                JToken jhasmore = jObject["has-more"];
                JToken joffset = jObject["offset"];
                JToken jcompanies = jObject["companies"];

                if (jhasmore.ToString().ToLower() == "true")
                    hasmore = true;
                else
                    hasmore = false;

                // creates offset parameter for next request
                offset = string.Format("&offset={0}", joffset.ToString());

                // run through each returned company collection
                foreach (var item in jcompanies.ToList())
                {
                    var name = item["properties"]["name"]["value"].ToString();
                    var address = item["properties"]["address"]["value"].ToString();
                }
            }

            counter++;
        }
        while (hasmore);
    }

I'm using JSON.net to process the JSON request. And while it is not a full deserialization, it allows me to retrive the data that I need on a item[key] basis.

Retrieving contacts is the exact same process. The only thing that changes is the URL that we will use to make the request. For a full list of HubSpot API URL's, you can read their documentation further right here.

Walter G. is a software engineer, startup co-founder, former CTO of several tech companies and currently teaches programming for a coding bootcamp. He has been blogging for the past 5 years and is an avid BMX rider, bio-hacker and performance enthusiast.
Buy me a coffeeBuy me a coffee
If you read this far, then I hope you enjoyed this post and found it useful! Consider adding to my daily coffee funds to continue to provide better and more helpful articles in the future!
Maybe later

Discussion / Comments / Questions

P
Phil Jeffrey
2/13/2018 11:21:14 PM
Hi Walter, thanks for the code above. I'm trying to extract a list of the property names from the Companies API (i.e. "name", "address" etc), not the values for a record. Do you know the correct syntax for extracting the property names from the JSON?
Walter G.
11/4/2018 10:10:41 PM
Send me a message and we can discuss further!
V
Victor
4/20/2018 8:41:06 AM
Good article but did not get any company back. {"has-more":false,"offset":0,"companies":[]}. Anything I missed?
Walter G.
11/4/2018 10:10:16 PM
I'd need to see more. Feel free to message me any info and I can take a look.

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment