Create Contact in C#


#1

Does anyone have an example on how to create a Contact in HubSpot using C#?

New to the HubSpot. What am I doing wrong here? How do I add properties like email and so on?

string emailAddress = "test@test.com"
Uri myUri = new Uri(String.Format(HubSpotURLFormat, string.Format(“contact/createOrUpdate/email/{0}/?hapikey=XXXXXXXXXXXXXX/”, emailAddress)));

        WebRequest myWebRequest = WebRequest.Create(myUri);
        //HttpWebRequest myWebRequest = HttpWebRequest.Create(myUri) as HttpWebRequest;

        myWebRequest.Headers.Add("Authorization", "apikey " + ApiKey);
        myWebRequest.ContentType = "text/json";
        //post new subscriber
        myWebRequest.Method = "POST";


        using (Stream reqStream = myWebRequest.GetRequestStream())
        {
            if (reqStream == null)
            {
                throw new HubSpotException("GetRequestStream stream is null");
            }

            using (var streamWriter = new StreamWriter(myWebRequest.GetRequestStream()))
            {
                var req = new
                {
                    ??????????????
                };
                string json = JsonConvert.SerializeObject(req, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            reqStream.Close();
        }
        return myWebRequest.GetResponse() as HttpWebResponse;
    }

#2

Hi @va69,

Here’s a working example, written using the RestSharp library. This example is just for learning/demonstration, and isn’t production-ready:

using System;
using RestSharp;

namespace ContactsUpdate
{
    class Program
    {
        static void Main(string[] args)
        {
            var emailAddress = "test@test.com";
            var hapiKey = "{YOUR_HAPI_KEY_HERE}";

            var client = new RestClient("https://api.hubapi.com/");
            var request = new RestRequest("contacts/v1/contact/createOrUpdate/email/{email}", Method.POST);
            request.AddUrlSegment("email", emailAddress);
            request.AddQueryParameter("hapikey", hapiKey);
            request.RequestFormat = DataFormat.Json;

            request.AddBody(new {
                properties = new[] {
                    new { property = "firstname", value = "TestFirst"},
                    new { property = "lastname", value = "TestLast"}
                }
            });

            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

            Console.ReadLine();
        }
    }
}