I want to know the syntax for writing the POST request for the whats app cloud api using c#

Viewed 22

The request format is like this provided by Facebook

'{
   "messaging_product": "whatsapp",
   "recipient_type": "individual",
   "to": "PHONE_NUMBER",
   "type": "text",
   "text": { // the text object
         "preview_url": false,
         "body": "MESSAGE_CONTENT"
   }
 }'

I have written a code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

  namespace WhatsAppCloudApiDemo
  {
    public class Post
    {
       public string messaging_product { get; set; }
       public string recipient_type { get; set; }
       public string to { get; set; }
       public string type { get; set; }
       public string text { get; set; }
    }
  }

And the request is like this

 Post newPost = new Post()
            {
                messaging_product = "whatsapp",
                recipient_type = "individual",
                to = number,
                type = "text",
                text = message
            };

            var newPostJson = JsonConvert.SerializeObject(newPost);
            Console.WriteLine(newPostJson);
            var payLoad = new StringContent(newPostJson, Encoding.UTF8, "application/json");
            var result = client.PostAsync(endpoint, payLoad).Result.Content.ReadAsStringAsync().Result; 
            Console.WriteLine(result);

But I'm getting an error saying the Parameter should be a JSON object. I need to know the proper way to write the request for the below as it is object inside an object

"text": { // the text object "preview_url": false, "body": "MESSAGE_CONTENT" }

1 Answers

The API should accept the request if you craft it like below. The text item itself has properies so it will be a class. I've arbitrarily named it "TextItem".

  namespace WhatsAppCloudApiDemo
  {
    public class Post
    {
       public string messaging_product { get; set; }
       public string recipient_type { get; set; }
       public string to { get; set; }
       public string type { get; set; }
       public TextItem text { get; set; }
    }

    public class TextItem
    {
        public bool preview_url { get; set; }
        public string body { get; set; }
    }
  }

and then initialize newPost like:

 Post newPost = new Post()
    {
        messaging_product = "whatsapp",
        recipient_type = "individual",
        to = number,
        type = "text",
        text = new TextItem { body = message, preview_url = false }
    };
Related