Solved

How to send a JSON object to my API through customization project ?

  • 10 November 2023
  • 1 reply
  • 120 views

Userlevel 1
Badge

I have a customization project which includes a custom JSON object which i created.

foreach (PXResult<POLine> result in polineview.Select()){

POLine line = result;
if(order.OrderNbr == line.OrderNbr) {

// Sample JSON object
var sampleJsonObject = new
{
OrderNbr = order.OrderNbr,
CustomerOrderNo = "CS0005",
CusomterOrderLineField = new
{
PartNo = "P002",
UnitCost = line.CuryUnitCost,
InventoryID = line.InventoryID
}
};

string json = Newtonsoft.Json.JsonConvert.SerializeObject(sampleJsonObject);

PXTrace.WriteInformation(json);

}
}

JSON Data:

{
"OrderNbr":"000453",
"CustomerOrderNo":"CS0005",
"CusomterOrderLineField":{
"PartNo":"P002",
"UnitCost":367.640000,
"InventoryID":18066
}
}

My API is http://testinstance/api/InsertTestPO

I have an action called ReleaseFromHold. When i perform this action I want to send this json object data to my above mentioned API to perform a POST request through the customization project itself.

How can I do it ?

icon

Best answer by paengesser82 11 November 2023, 03:42

View original

1 reply

Userlevel 4
Badge +1

Hi @ifelix!

Sending an http post request from Acumatica is petty much the same as sending one from any .net application.
Here is a code sample showing how to do it inside an Acumatica Action but the same process will work in other places also.

        public PXAction<MasterTable> apiPostTest;
[PXUIField(DisplayName = "API Post Test")]
[PXButton]
public virtual void ApiPostTest()
{
// your url goes here
string url = "https://httpbin.org/post";
// your json body text goes here
string jsonBody = "{ \"message\" : \"post message\"}";

using (var client = new HttpClient())
{
var content = new StringContent(jsonBody, Encoding.UTF8,
"application/json");

// send the post request and store the return value in results
var result = client.PostAsync(url, content).Result;

// check to see if the post request was successful
if (result.IsSuccessStatusCode)
{
var returnString = result.Content.ReadAsStringAsync();
}
else
{
// a non success http status code was returned, i.e. not 200
}
}
}

The above code uses HttpClient which System.Net.Http dll/using statement. For me visual studio will automatically add that to my project.
Also note, the above code runs the request synchronously, if you want to run it asynchronously that is also possible.

Let me know if you run into any issues or have follow up questions!

Philip Engesser

 

Reply


About Acumatica ERP system
Acumatica Cloud ERP provides the best business management solution for transforming your company to thrive in the new digital economy. Built on a future-proof platform with open architecture for rapid integrations, scalability, and ease of use, Acumatica delivers unparalleled value to small and midmarket organizations. Connected Business. Delivered.
© 2008 — 2024  Acumatica, Inc. All rights reserved