Sample: GET (Query), PUT (Update) and POST(Create) in C#

Highlighted
Moderator

Sample: GET (Query), PUT (Update) and POST(Create) in C#

 


This code is set up for a contact, but is easily adapted for any of the REST APIs that exist.

 

GET:

// Note: Remember to add using System.Net;

 

// Create LoginCreditials

CredentialCache LoginCredentials = new CredentialCache();

 

// Add a new credential for this account

LoginCredentials.Add(new Uri(https://api.constantcontact.com/ws/customers/USERNAME),

    // Set up URI for API site

    Basic, // Basic login type

    new NetworkCredential(APIKey + % + Username, // Set up API Username (APIKey%Username)

        Password)); // Password 

 

// Create WebRequest, this is a factory class with a static constructor

// You can not use new, all requests must be created with WebRequest.Create

WebRequest Request = WebRequest.Create(ContactURI); // URI for the GET 

 

// Set Request credentials

Request.Credentials = LoginCredentials;

 

// Send GET request

// Recast the response to HttpWebResponse for correct processing

// Place in a try block to ensure that any errors are caught

try

{

    HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

 

    // Process the Response as needed

    // This is a generic StreamReader to read the entire response in

    // GetResponseStream can be recast to any of the Stream types

    // Note: Remember to add using System.IO

    StreamReader Reader = new StreamReader(Response.GetResponseStream()); // Read the entire XML response to a string string

    XMLResponse = Response.StatusCode + + Response.StatusDescription + + Reader.ReadToEnd();

 

    // Close Reader

    Reader.Close();

 

    // Close the response to free up the system resources

    Response.Close();

 

    return XMLResponse;

}

 

catch (WebException e)

{

    // Get the web exception type, error number returned here

    return WebException: + e.Status + + e.Message;

}

 

catch (Exception e)

{

    // Get the exception type

    return Exception: + e.Message;

}

 

PUT:

// Note: Remember to add using System.Net;

// Create LoginCreditials

CredentialCache LoginCredentials = new CredentialCache();

 

// Add a new credential for this account

LoginCredentials.Add(new Uri(https://api.constantcontact.com/ws/customers/USERNAME),

 

    // Set up URI for API site

    Basic// Basic login type

    new NetworkCredential(APIKey + % + Username, // Set up API Username (APIKey%Username)

        Password)); // Password 

 

// Create WebRequest

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(ContactURI);

 

// URI for the PUT 

// Set Request to be a PUT

Request.Method = PUT;

 

// Set the ContentType property.

Request.ContentType = application/atom+xml;

 

// Set Request credentials

Request.Credentials = LoginCredentials;

 

// Set up XML String for the PUT

// Long string with quotes, use an absolute string with literals

string XMLData = ;

 

// Set up the XML Document, application dependant 

// Convert XMLData to byteArray for posting

byte[] byteArray = Encoding.UTF8.GetBytes(XMLData);

 

// Send PUT request

// Recast the response to HttpWebResponse for easier processing

// Place in a try block to ensure that any errors are caught

try

{

 

    // Set the ContentLength portion of the header

    Request.ContentLength = byteArray.Length; string XMLResponse = Bytes to send: + byteArray.Length;

 

    // Create a stream for the PUT Request

    Stream streamRequest = Request.GetRequestStream();

 

    // Write the data to the stream.

    // Note: Remember to add using System.IO

    streamRequest.Write(byteArray, 0, byteArray.Length);

    streamRequest.Close();

    HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

 

    // Process the Response as needed

    // This is a generic StreamReader to read the entire response in

    // You can recast this as any type of stream derivative

    StreamReader Reader = new StreamReader(Response.GetResponseStream());

 

    // Read the entire XML response to a string

    // Note there may not be a XML response for a successful PUT

    XMLResponse += Response.StatusCode + + Response.StatusDescription + + Reader.ReadToEnd();

 

    // Close Reader

    Reader.Close();

 

    // Close the response to free up the system resources

    Response.Close();

    return XMLResponse;

}

catch (WebException e)

{

    // Get the web exception type and response code

    return WebException: + e.Status + With response: + e.Message;

}

catch (Exception e)

{

    // Get the exception type

    return Exception: + e.Message;

}

 

POST:

// Note: Remember to add using System.Net;

// Create LoginCreditials

CredentialCache LoginCredentials = new CredentialCache();

 

// Add a new credential for this account

LoginCredentials.Add(new Uri(https://api.constantcontact.com/ws/customers/USERNAME),

    // Set up URI for API site

    Basic, // Basic login type

    new NetworkCredential(APIKey + % + Username, // Set up API Username (APIKey%Username)

        Password)); // Password 

 

// Create WebRequest

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(ContactURI);

 

// URI for the POST 

// Set Request to be a POST

Request.Method = POST;

 

// Set the ContentType property.

Request.ContentType = application/atom+xml;

 

// Set Request credentials

Request.Credentials = LoginCredentials;

 

// Set up XML String for the POST

// Long string with quotes, use an absolute string with literals string or a StringBuilder

XMLData = ;

 

// Set up the XML Document, application dependant 

 

// Convert XMLData to byteArray for posting

byte[] byteArray = Encoding.UTF8.GetBytes(XMLData);

 

// Send POST request

// Recast the response to HttpWebResponse for easier processing

// Place in a try block to ensure that any errors are caught

try

{

 

    // Set the ContentLength portion of the header

    Request.ContentLength = byteArray.Length; string XMLResponse = Bytes to send: + byteArray.Length;

 

    // Create a stream for the POST Request

    // Note: Remember to add using System.IO

    Stream streamRequest = Request.GetRequestStream();

 

    // Write the data to the stream.

    streamRequest.Write(byteArray, 0, byteArray.Length);

    streamRequest.Close();

    HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

 

    // Process the Response as needed

    // This is a generic StreamReader to read the entire response in

    // You can recast this as any type of stream derivative

 

    StreamReader Reader = new StreamReader(Response.GetResponseStream());

 

    // Read the entire XML response to a string

    // Note there may not be a XML response for a successful POST

    XMLResponse += Response.StatusCode + + Response.StatusDescription + + Reader.ReadToEnd();

 

    // Close Reader

    Reader.Close();

 

    // Close the response to free up the system resources

    Response.Close();

 

    return XMLResponse;

}

catch (WebException e)

{

    // Get the web exception type and response code

    return WebException: + e.Status + With response: + e.Message;

}

 

catch (Exception e)

{

    // Get the exception type

    return Exception: + e.Message;

}

 

Please feel free to post comments, corrections or suggestions.

 

Dave Berard
Senior Product Manager, Constant Contact
6 REPLIES 6
Highlighted
Moderator

I've updated the code to

I've updated the code to correctly reflect Basic Authentication over HTTPS. 

Dave Berard
Senior Product Manager, Constant Contact
Highlighted
Occasional Participant

Failed Attempt...

Hello! I have attempted to adapt your code to get the campaign information, yet am getting errors.


static void Main(string[] args)

        {

            string APIKey = "myAPIKeyHere"; // Obviously Correct API Key

            string myUsername = "Reelix";

            string myPassword = "myPassOverHere"; // Obviously Correct Pass

            string myString = getDetails(APIKey, myUsername, myPassword);

            Console.WriteLine(myString);

            Console.ReadLine();

        }


public static string getDetails(string APIKey, string myUsername, string myPassword)

        {

            CredentialCache LoginCredentials = new CredentialCache();



            LoginCredentials.Add(new Uri("http://api.constantcontact.com/ws/customers/" + myUsername), "Basic", new NetworkCredential(APIKey + "%" + myUsername, myPassword));



            WebRequest Request = WebRequest.Create("http://api.constantcontact.com/ws/customers/" + myUsername + "/campaigns");

            Request.Credentials = LoginCredentials;



            string XMLResponse;

            try

            {

                HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();



                StreamReader Reader = new StreamReader(Response.GetResponseStream()); // Read the entire XML response to a string string

                XMLResponse = Response.StatusCode + Response.StatusDescription + Reader.ReadToEnd();


                Reader.Close();



                Response.Close();



                return XMLResponse;

            }



            catch (WebException e)

            {

                return ("WebExecption: " + e.Status + "\n" + e.Message);

            }



            catch (Exception e)

            {

                return ("General Exception: " + e.Message);

            }

        }


 


The code compiles properly, but always returns: WebExecption: ProtocolError The remote server returned an error: (401) Unauthorized. Am I doing something wrong? - Reelix

Highlighted
Moderator

It looks like you are not

It looks like you are not using the correct protocol for your Authentication.  If you read our documentation on Authentication here, you'll notice that it requires you to use HTTPS for all requests.  Not using HTTPS will always result on a 401 as it will not be able to Authenticate you.  Changing the following lines will fix your code and it ran fine for me:


 


            LoginCredentials.Add(new Uri("https://api.constantcontact.com/ws/customers/" + myUsername), "Basic", new NetworkCredential(APIKey + "%" + myUsername, myPassword));



            WebRequest Request = WebRequest.Create("https://api.constantcontact.com/ws/customers/" + myUsername + "/campaigns");

Dave Berard
Senior Product Manager, Constant Contact
Highlighted
Occasional Participant

Hi Dave! My mistake! Your

Hi Dave!


My mistake! Your changes worked perfectly!


Thanks alot, and enjoy your day!


- Reelix

Highlighted
New Member

Just can't get it right...

I am trying to create a user control that allows users to subscribe to our newsletter. The control consists of a single textbox to capture the email address.


I would like to compare this email address to the contacts already in the contact list (id 30) to determine whether the user has subscribed already or not. If they are already subscribed, a message would display to say as much and if not, the user is added.


But I cannot seem to get the above code for getting a list of contacts working. I receive the following errors:

Error    3    ; expected       

Error    4    Invalid expression term ':'       


Please help :-/

Highlighted
CTCT Employee

Re: Just can't get it right...

The best way to determine if a contact exists would be to Search for a Contact by Email Address. If the contact is found is will return an try for that contact, otherwise it will not. This is the quickest way to determine if that contact exists anywhere in your account. Please note that this will search all lists in your account, so if that is your objective - searching by email address would be the recommended method.


 


If you are looking to determine if the contact is part of a particular list, you have a few options.


1) Perform the above search for a contact to determine if they exist at all. If that search returns an entry you can take the id from that and perform a get on https://api.constantcontact.com/ws/customers/{user-name}/contacts/{contact-id} and this will return contact details, including each list that they are subscribed to. (Recommended)


 


2) Retrieve the list members by performing a get on https://api.constantcontact.com/ws/customers/{user-name}/lists/{list-id}/members to determine if an email address is subscribed to that list.


 


I hope this was helpful, please let me know if you have any further questions.

David J

Developer Portal

View API documentation, code samples, get your API key.

Visit Page

Constant Contact Would Like To Hear From You!

We want to hear from customers like you about your favorite features and how they have helped your business or organization. Tell us by answering a few questions in...

Read More
Featured