Click here to Skip to main content
15,881,898 members
Articles / Programming Languages / C#
Tip/Trick

Implementation of TheTexting.com HTTP based RESTful API

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Sep 2015CPOL3 min read 10.2K   3   1
This tip will help you send SMS through API call by integrating TheTexting RESTful API

Introduction

This tip is useful to those who are trying to integrate & implement TheTexting RESTful API in their existing system or application. This tip focuses on implementation in C#. TheTexting.com provides RESTful API for sending bulk SMS to users all across the globe. They also provide dedicated long numbers so that the incoming messages and replies are received as well.

Background

Recently, I was asked by my client to develop a Windows desktop application in C# that will be able to send bulk SMS for their marketing purposes with dedicated numbers. I was to only develop the desktop interface and use some third-party API for actual SMS services. Upon researching for the optimum solution for the backend service provider, I found TheTexting.com API. It was perfect as per my client's requirements and their pricing was very reasonable too. So I decided to give this provider a shot and boy, I am glad that I did. Their service has been extremely impressive and their customer support staff is very helpful and answered all my queries in a timely manner.

Using the Code

For this tip, I will be using Windows console application to demostrate the integration of HTTP based RESTful API in a .NET application. I recommend downloading & running the project code attached to this tip to see a working example.

First of all, in order to use this API, a developer will need to procure an API key & API secret key upon registration on the TheTexting portal. These keys will yield access to the API methods and can be retrieved from the API settings page on your portal.

The official API documentation can be viewed by click here: TheTexting API Documentation

In this project, I have created a single class for all the API calls. Some of these API calls are GET request based while some are POST request based (see official documentation for details). The response can be either in XML or JSON based on your request URL:

For JSON:

https://www.thetexting.com/rest/sms/json

For XML:

https://www.thetexting.com/rest/sms/xml

For the sake of keeping this tip short & concise, I will be demonstrating the usage of only one of the methods from the class and therefore subsequently, making a call to only one of the APIs.

To Send SMS

The easiest way to send an SMS is arguably to copy and paste the following URL in your web browser:

https://www.thetexting.com/rest/sms/json/Message/Send?api_key={YOUR API KEY}
&api_secret={YOUR API SECRET}&from={YOUR DEDICATED NUMBER}&to={YOUR DESTINATION NUMBER}
&type={MESSAGE TYPE}&text={MESSAGE TEXT}

However, if you need to send the SMS programmatically, i.e., through your own application, then you need to integrate the API in your application.

Below is the method to send SMS which uses HttpClient class for sending HTTP POST request and prints the response.

C#
class TheTextingAPI
  {
    public static void SendSMS(string ApiKey, string ApiSecret, 
			string from, string to, string type, string text)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    #region :: Append Base Header & Authentication ::
                    client.BaseAddress = 
                    new Uri("https://www.thetexting.com/rest/sms/json/message/send");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add
                    	(new MediaTypeWithQualityHeaderValue("application/json"));
                    #endregion

                    #region :: Append Data to Model
                    SendMessageRequestModel objRequestModel = new SendMessageRequestModel();
                    objRequestModel.api_key = ApiKey;
                    objRequestModel.api_secret = ApiSecret;
                    objRequestModel.from = from;
                    objRequestModel.to = to;
                    objRequestModel.type = type;
                    objRequestModel.text = text;
                    #endregion

                    #region :: Initializing Http Request & Serialize Model::
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "send");
                    string jsonString = JsonConvert.SerializeObject(objRequestModel, 
                    	Newtonsoft.Json.Formatting.None, new JsonSerializerSettings 
                    	{ NullValueHandling = NullValueHandling.Ignore });
                    request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    #endregion

                    #region :: Http Post Request & Deseralize Json Response to Model
                    var response = client.SendAsync(request).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var jsonResponse = response.Content.ReadAsStringAsync().Result;
                        var objInsightResponse = JsonConvert.DeserializeObject
                        	<GenericResponse<SendMessageResponseModel>>(jsonResponse);
                        if (objInsightResponse.Response != null)
                        {
                            Console.WriteLine(" XX--- Response Starts ---XX");
                            Console.WriteLine("Message Successfully Sent");
                            Console.WriteLine("Message ID : {0}", 
				objInsightResponse.Response.message_id);
                            Console.WriteLine("Message Count : {0}", 
				objInsightResponse.Response.message_count);
                            Console.WriteLine("Message Price : {0}", objInsightResponse.Response.price);
                            Console.WriteLine(" XX--- Response Ends ---XX");
                        }
                        else
                        {
                            Console.WriteLine("Response was null because : 
						{0}", objInsightResponse.ErrorMessage);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Console.Write("An exception occurred: " + ex.Message);
            }
        }
   }

To use the above method, all you need to do is to pass the required parameters to the method.

TheTextingAPI.SendSMS("ApiKey123","ApiSecret456","1987654321",
"1987654321","text","Hello World!")

Please see the attached project for complete list of calls.

Conclusion

This tip has provided you a tutorial on how to integrate TheTexting API in your C# application. You may modify the application as per your liking and requirement.

Please note that I have not included all the API calls provided by the API provider in this project. I have just included 6, 7 calls so that the user gets the basic idea on how to integrate TheTexting HTTP based RESTful API in their project. This is my first tip. Hopefully, it will be useful to someone.

Links

History

  • Version 1,0 - Tutorial creation - Project tested on Windows 7 running Visual Studio 2013

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
I am a software developer by profession, having worked on .NET technologies for more than 2 years now. I also do freelancing projects.

Comments and Discussions

 
QuestionCallback Response Pin
Member 143266553-Dec-19 17:53
Member 143266553-Dec-19 17:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.