Skip to main content

Notifications

Announcements

No record found.

Finance | Project Operations, Human Resources, ...
Answered

API call throws exception on bad request

(1) ShareShare
ReportReport
Posted on by 117
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,201 Super User 2024 Season 2 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 117 on at
    API call throws exception on bad request
    Thank You, Anthony Blake.
     
    your solution worked for me.
  • ShahzaibAhmed52 Profile Picture
    ShahzaibAhmed52 117 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,264 Super User 2024 Season 2 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,201 Super User 2024 Season 2 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 117 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,264 Super User 2024 Season 2 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 117 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

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,703 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,433 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans