web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

Custom Webservice For Accepting Message in JSON message

(0) ShareShare
ReportReport
Posted on by 2,546

D365 Finance & Operations Custom Webservice For Accepting Message in JSON message 

Hello Friends,

Greetings 

I have a requirement.Third party developers want to consume D365 FO API in their system..He will input JSON message in body section.I want create a REST JSON custom webservice.

Kindly guide me.i am not able to find any tutorials.

  1. {  
  2.     "employee": {  
  3.         "name":       "sonoo",   
  4.         "salary":      56000,   
  5.         "married":    true  
  6.     }  
  7. }  

Best Regards,

Piyush

I have the same question (0)
  • Sukrut Parab Profile Picture
    71,710 Moderator on at

    What problem you are facing ? Just write a custom service as you write usually and return data set is going to be in JSON format available at JSON endpoint. Your external party is going to  Consume it.

  • Piyush Adhikari Profile Picture
    2,546 on at

    Sir, Thanks for your reply.

    Sir,

    Customer will consume D365 REST JSON and push the message in below format

    {

    "id": "0001",

    "type": "donut",

    "name": "Cake",

    "ppu": 0.55,

    "batters":

    {

    "batter":

    [

    { "id": "1001", "type": "Regular" },

    { "id": "1002", "type": "Chocolate" },

    { "id": "1003", "type": "Blueberry" },

    { "id": "1004", "type": "Devil's Food" }

    ]

    },

    "topping":

    [

    { "id": "5001", "type": "None" },

    { "id": "5002", "type": "Glazed" },

    { "id": "5005", "type": "Sugar" },

    { "id": "5007", "type": "Powdered Sugar" },

    { "id": "5006", "type": "Chocolate with Sprinkles" },

    { "id": "5003", "type": "Chocolate" },

    { "id": "5004", "type": "Maple" }

    ]

    }

    i am still confused. He will POST the JSON string in above format . How i will develop the REST JSON webservice in D365 which will accept JSON string and insert records into the table.

    Customer is not ready to purchase LOGICS APPS also.

  • Verified answer
    Martin Dráb Profile Picture
    237,807 Most Valuable Professional on at

    The first step, as usual, is reading the documentation. It'll tell you how to build custom services in general. As you can see there, custom services in D365FO have two endpoints and one of them is JSON-based (which is what you want).

    The key part is writing your service operation. It'll be a method accepting a singe data contract object and do the inserts. The data contract class will have (among primitive values such as "name") two collections of objects of another data contract class, "batter" and "topping".

    Notice that we don't bother working with the data serialized to JSON and handling deserialization by ourselves - it's covered by D365FO automatically.

  • Piyush Adhikari Profile Picture
    2,546 on at

    OK thanks Sir.

    I will try and get back to you soon.

  • Piyush Adhikari Profile Picture
    2,546 on at

    Hello Sir,

    I tried the same thing using service samples from GIT library

    For testing purpose i created one data contract class and service class as mentioned below :

    [DataContractAttribute('JSONTestHeaderContract')]
    class JSONTestHeaderContract
    {
        str ordernumber;
        str customerCode;
        [DataMemberAttribute('ordernumber')]
        public str ordernumber(str _ordernumber = ordernumber)
        {
            ordernumber = _ordernumber;
            return ordernumber;
        }
    
        [DataMemberAttribute('customerCode')]
        public str customerCode(str _customerCode = customerCode)
        {
            customerCode = _customerCode;
            return customerCode;
        }
    
    }
    
    
    class JSONTestService
    {
        [AifCollectionTypeAttribute('return', Types::Class, classStr(JSONTestHeaderContract)),
             AifCollectionTypeAttribute('_keys', Types::Class, classStr(JSONTestHeaderContract))]
        public List operation(List _keys)
        {
            List    list = new List(Types::Class);
            ListEnumerator keysEnumerator;
            JSONTestHeaderContract info = new JSONTestHeaderContract();
            info.ordernumber('Order Number 001');
            info.customerCode('Customer Code 001');
            list.addStart(info);
            keysEnumerator = _keys.getEnumerator();
            JSONTestHeaderContract  JSONTestHeaderContractCurrent;
            while(keysEnumerator.moveNext())
            {
                JSONTestHeaderContractCurrent = keysEnumerator.current();
            }
            return list;
        }
    
    }

    Luckily it is working fine when i am not defining any input parameters above service class and using below code for consuming it in .Net.

    class Program
        {
            // In the AOT you will find UserSessionService in Service Groups and AifUserSessionService under Services.
            public static string sessionUrl = "/api/services/JSONTestServiceGroup/JSONTestService/JSONTestService";
           
            static void Main(string[] args)
            {
                string GetUserSessionOperationPath = string.Format("{0}{1}", ClientConfiguration.Default.UriString.TrimEnd('/'), sessionUrl);
                
                var request = HttpWebRequest.Create(GetUserSessionOperationPath);     
                // If you call GetAuthenticationHeader with true you will the auth via AAD Web App, otherwise via Native AAD App
                request.Headers[OAuthHelper.OAuthHeader] = OAuthHelper.GetAuthenticationHeader(true);
                request.ContentType = "application/json; charset=utf-8";
                request.Method = "POST";
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(responseStream))
                        {
                            string responseString = streamReader.ReadToEnd();
    
                            Console.WriteLine(responseString);
                        }
                    }
                }
    
                Console.ReadLine();
            }
    
        }

    and returning me JSON in response in below format

    {
    	"$id": "1",
    	"ordernumber": "Order Number 001",
    	"customerCode": "Customer Code 001"
    }

  • Piyush Adhikari Profile Picture
    2,546 on at

    But the issue is there when i am trying to post JSON C# then it is throwing an error 502 ...

    class Program
        {
            // In the AOT you will find UserSessionService in Service Groups and AifUserSessionService under Services.
            public static string sessionUrl = "/api/services/JSONTestServiceGroup/JSONTestService/JSONTestService";
           // public static string sessionUrl = "/api/services/UserSessionService/AifUserSessionService/GetUserSessionInfo";
    
    
            static void Main(string[] args)
            {
                string GetUserSessionOperationPath = string.Format("{0}{1}", ClientConfiguration.Default.UriString.TrimEnd('/'), sessionUrl);
                
                var request = HttpWebRequest.Create(GetUserSessionOperationPath);     
                // If you call GetAuthenticationHeader with true you will the auth via AAD Web App, otherwise via Native AAD App
                request.Headers[OAuthHelper.OAuthHeader] = OAuthHelper.GetAuthenticationHeader(true);
                request.ContentType = "application/json; charset=utf-8";
                request.Method = "POST";
                request.ContentLength = Encoding.UTF8.GetByteCount("[{\"ordernumber\": \"en-US\",\"customerCode\": \"ABC\"}]");
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    string json = "[{\"ordernumber\": \"en-US\",\"customerCode\": \"ABC\"}]";
                    Debug.Write(json);
                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(responseStream))
                        {
                            string responseString = streamReader.ReadToEnd();
    
                            Console.WriteLine(responseString);
                        }
                    }
                }
    
                Console.ReadLine();
            }
    
        }

  • Piyush Adhikari Profile Picture
    2,546 on at

    error is

    The remote server returned an error: (500) Internal Server Error.

    thats it ...no other info

  • Martin Dráb Profile Picture
    237,807 Most Valuable Professional on at

    How does your method look like? You mentioned only operation() method accepting a list and returning a list, but then you talked about a method without parameters returning a single object and now you're passing something strange as the parameter.

    If you're now calling operation(List _keys), the input JSON should be something like this:

    {
      "_keys":
      [
        {
    		"ordernumber": "en-US",
    		"customerCode": "ABC"
    	}
      ]
    }

    By the way, you can usually find more details about errors in Event Log; the HTTP code isn't the only thing available to you.

  • Piyush Adhikari Profile Picture
    2,546 on at

    how i can identify that what should be the exact JSON format for input ? is there any way ?

  • Piyush Adhikari Profile Picture
    2,546 on at

    Dear Sir,

    Its is working fine now but i have few doubts regarding this process?

    First one is

    How can i identify that what should be the exact JSON format for input ? is there any way ?

    Second one is

    My input message should be in below format i don't want the the keyword or TAG "_keys" how can i avoid it ?

    [{
    		"CardNumber": "55*********",
    		"Type": "1",
    		"BusinessType": 1,
    		"OrderID": 180,
    		"VoucherCount": 0,
    		"Denomination": 0,
    		"Amount": 2000,
    		"IsOTP": "N",
    		"CustomerName": "",
    		"Mobile": "",
    		"Email": "",
    		"ProductType": "C"
    	},
    
    	{
    		"CardNumber": "CG*********",
    		"Type": "2",
    		"BusinessType": 1,
    		"OrderID": 180,
    		"VoucherCount": 0,
    		"Denomination": 0,
    		"Amount": 500,
    		"IsOTP": "N",
    		"CustomerName": "",
    		"Mobile": "",
    		"Email": "",
    		"ProductType": "C"
    	}
    ]

    Third one is

    In response message, Tag "$id" is coming in JSON response how can i remove it ? is possible?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 664 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 522 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 303 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans