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

API call throws exception on bad request

(1) ShareShare
ReportReport
Posted on by 123
Hi, 
 
I am consuming an API to send some data to an external entity. I get a 400 Bad request error and my code jumps to an exception directly and I have no idea what's wrong with the request. I sent the same request through Postman I got an error message in the response. How can get the same results as Postman in my X++ code?

Here is the sample of code that I am using to call the API.
 
System.Net.HttpWebRequest request;System.IO.Stream stream;System.Exception sysEx;request = System.Net.WebRequest::Create('URL') as System.Net.HttpWebRequest;request.Method = 'POST';request.ContentType = 'application/json';System.Net.WebHeaderCollection headerCollection = request.Headers;headerCollection.Set('Name', 'Value');var utf8 = System.Text.Encoding::get_UTF8();var byteArrayPayload = utf8.GetBytes('{key1:value1,key2:value2}');try        {using (System.IO.Stream dataStream = request.GetRequestStream()){dataStream.Write(byteArrayPayload, 0, byteArrayPayload.Length);}using (System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse){stream = response.GetResponseStream();System.IO.StreamReader reader = new System.IO.StreamReader(stream);str responseBody = reader.ReadToEnd();}}catch(sysEx){throw;}
 
  • Anthony Blake Profile Picture
    Anthony Blake 2,310 Super User 2025 Season 1 on at
    API call throws exception on bad request
    Excellent news!
     
    Please mark my solution as verified to help future users/google searchers find their solution
  • Suggested answer
    ShahzaibAhmed52 Profile Picture
    ShahzaibAhmed52 123 on at
    API call throws exception on bad request
    Thank You, Anthony Blake.
     
    your solution worked for me.
  • ShahzaibAhmed52 Profile Picture
    ShahzaibAhmed52 123 on at
    API call throws exception on bad request
    System.Net.HttpWebRequest request;
    System.IO.Stream stream;
    System.Exception sysEx;
    
    request = System.Net.WebRequest::Create('URL') as System.Net.HttpWebRequest;
    request.Method = 'POST';
    request.ContentType = 'application/json';
    
    System.Net.WebHeaderCollection headerCollection = request.Headers;
    headerCollection.Set('Name', 'Value');
    
    var utf8 = System.Text.Encoding::get_UTF8();
    var byteArrayPayload = utf8.GetBytes('{key1:value1,key2:value2}');
    
    try        
    {
    	using (System.IO.Stream dataStream = request.GetRequestStream())
    	{
    		dataStream.Write(byteArrayPayload, 0, byteArrayPayload.Length);
    	}
    	
    	using (System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
    	{
    		stream = response.GetResponseStream();
    		System.IO.StreamReader reader = new System.IO.StreamReader(stream);
    		str responseBody = reader.ReadToEnd();
    	}
    }
    catch(sysEx)
    {
    	throw;
    }
     
  • Layan Jwei Profile Picture
    Layan Jwei 7,711 Super User 2025 Season 1 on at
    API call throws exception on bad request
    Hi Shahzaib,
     
    Can you please re-share your code in a proper format?
    Also did you debug and see at which line of code does it fail? And when it goes to the catch did you see in the debugger watch what ex is returning?

    ex.Message should return the error. Also did you try after the catch to put info(responseBody) and check if the result of postman appears?
     
    Thanks,
    Layan Jweihan
  • Verified answer
    Anthony Blake Profile Picture
    Anthony Blake 2,310 Super User 2025 Season 1 on at
    API call throws exception on bad request
    If you can catch a System.Net.WebException, you should have access to the response body, which is what you see in postman.
     
     
    This is how to do it in C#, it should be transferrable to X++:
     
     
    System.Net.WebException ex;
    try
    {
    // call the API
    }
    catch(ex)
    {

    // read the response stream as you do on success, but from from ex.Response.GetResponseStream()
    }
     
  • ShahzaibAhmed52 Profile Picture
    ShahzaibAhmed52 123 on at
    API call throws exception on bad request
    I have tried to throw ex.message as well but its the same. All I want to achive is to get the response Json and Parse it to create a log.
    ​​​​​​​
  • Suggested answer
    Layan Jwei Profile Picture
    Layan Jwei 7,711 Super User 2025 Season 1 on at
    API call throws exception on bad request
    Hi Shahzaib,
     
    It's because you are throwing nothing in the catch.
     
    Try this
    System.Exception ex; 
    try 
    {
         //Logic
    catch(ex)
          error(ex.Message);
    }
     
    Thanks,
    Layan Jweihan
    Please mark this answer as "Verified" if it solved your issue. In order to help others who will face a similar issue in the future
  • ShahzaibAhmed52 Profile Picture
    ShahzaibAhmed52 123 on at
    API call throws exception on bad request
    I get a proper response that the data is invalid from postman with status code 400 bad request. Thats the same I want to do in X++ to maintain a log.

    If the data is valid it works fine. 
  • Judy Profile Picture
    Judy Microsoft Employee on at
    API call throws exception on bad request
    Hi,
     
    What the error messages you got when you sent the request through postman.
    The HTTP 400 Bad Request error occurs when the request query parameter or request body content is invalid.
    Could you please check the response body to find out which part of the request is not valid.

    Best Regards,
    Judy

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

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Vahid Ghafarpour – Community Spotlight

We are excited to recognize Vahid Ghafarpour as our February 2025 Community…

Tip: Become a User Group leader!

Join the ranks of valued community UG leaders

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,494 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,305 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans