Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Step by Step Guide to Create Restful API for Dynamics AX Data

Dynamics AX is a native program built by Microsoft for ERP processing and solutions. It has inbuilt systems that help companies organize, automate, and optimize their data processing systems. One aspect of data processing is its seamless integration with other programs connected to the ERP ecosystem.

Building this connectivity between programs is done with API. Basically, the Restful Api can be used when you need to integrate between two applications. In this blog, I have covered steps to create a Restful API to integrate with Microsoft Dynamics AX Data and how it can be verified through Postman.

Restful API

A Restful API is used for integrating two applications together so that they work in proper synchronization. If you are interested in creating your own ASP .NET application, then the Restful API will be an important tool in helping you to do so.

The format of the Restful API URLs is: {Localhost:IP/ Domain site}/api/{Controller}

Methods:

The methods required for creation of your Restful API are:

Create ASP.Net Application

Create your ASP.NET application in Visual Studio 2015 and follow the steps as provided below Here are the steps needed to accomplish this:

  1. Go to File > New > Project
  2. Select the Visual C# project category and then select ASP.NET Web Application (.NET Framework)
  3. Name your project RestAPI and click OK
  4. Select the Empty project template and click OK (don’t check any boxes to add core references)

Add NuGet Packages

For the next step, you need to get a few NuGet packages. Use the following commands in the Package Manager console to install them:

  • Install-Package Microsoft.AspNet.WebApi
  • Install-Package Microsoft.Owin.Host.SystemWeb
  • Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Add Startup class

Now right click on your project and select Add > Class and name it as Startup.cs. Copy and paste the following code into the new file:

using System.Web.Http;
using Newtonsoft.Json.Serialization;
using Owin;

namespace RestAPI
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            app.UseWebApi(config);
        }
    }
}

In the code above, the parts highlighted in yellow are used to remove the XmlFormatter (which is the default output formatter), and instead configure the JsonFormatter to camel-case property names and to use UTC time for dates.

API with Static Data

Add Controller

Now, you need to add a Controllers folder to your project. Once done, right click on the Controllers folder and select Add > New Items On the left select Visual C# > Web > Web API. Then click on Web API Controller Class (v2.1), name it Controller.cs, and click Add.

Now you should have a controller with methods to Get, Post, Put, and Delete list items. Let’s test it.

Press F5 to launch your API. After the browser opens, add /api/listitems to the end of the URL and hit Enter

Add Model

Create a Resource and the ASP.NET Web API Actions

Now let’s make this API actually do something useful. For this part, you’ll create a list item resource and wire up all of the controller actions so you can create, read, update, and delete items.

Go ahead and create a Models folder in your project and add a CustomListItem.cs class. It should look like this:

The structure of the CustomListItem.cs is to be defined as per the data being posted.

Below is the CustomListItem.cs for your reference:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RestAPI.Models
{
    public class CustomListItem
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }
}

Add Get/Post methods in Controller

Back in your ListItemsController class, add a private static property to store your list items in memory. Add the private property inside the class declaration.

private static List<CustomListItem> _listItems { get; set; } = new List<CustomListItem>();
You will also need to add a using statement to the top of the controller.
using RestAPI.Models;
To read items, update the Get method as shown below:
public IEnumerable<CustomListItem> Get()
 {
            return _listItems;
 }
To create items, update the Post method as specified below:
public HttpResponseMessage Post([FromBody]CustomListItem model)
{
            if (string.IsNullOrEmpty(model?.Text))
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            var maxId = 0;
            if (_listItems.Count > 0)
            {
                maxId = _listItems.Max(x => x.Id);
            }
            model.Id = maxId + 1;
            _listItems.Add(model);
            return Request.CreateResponse(HttpStatusCode.Created, model);
}

Build and run the application, and test the post method in Postman as below:

Get Method

Post Method

Get Method after Post

API with AX Data

Add Controller

Now, you must add a Controller folder to your project. Then right click on the Controllers folder and select Add > New Item.On the left select Visual C# > Web > Web API. Then click on Web API Controller Class (v2.1), name it Controller.cs, and click Add.

Now you should have a controller with methods to Get, Post, Put, and Delete list items. Let’s test it.

Press F5 to launch your API. After the browser opens, add /api/AxTrainings to the end of the URL and hit Enter

Add Model

Create a Resource and the ASP.NET Web API Actions

Add AxTrainings class in RestAPI.Models as shown below:

public class AXTrainings
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string TrainingDate { get; set; }
 }

Connect with AX using Business connector

To connect with the business connector, add the reference of business connectors’ dll file from Bin folder of AX client as shown below:

C:\Program Files (x86)\\60\Client\Bin

Add the using statement as below:

using Microsoft.Dynamics.BusinessConnectorNet;

Add Get/Post methods in Controller

Back in your AxTrainingsController class, add a private static property to store your list items in the memory. Add the private property inside the class declaration.

private static List<AXTrainings> _AxTrainings { get; set; } = new List<AXTrainings>();

You will also need to add a using statement to the top of the controller.

using RestAPI.Models;

To read AxTrainings from AX, update the Get method as below:

public IEnumerable<AXTrainings> Get()
        {
            // return new string[] { "value1", "value2" };
            AXTrainings objAXTrainings;
            Axapta ax;
            AxaptaRecord axRecord;

            string tableName = "Dev_Trainings";
            string strId = "Id";
            string strName = "Name";
            string strTrainingDate = "TrainingDate";

            object fieldId, fieldName, fieldTrainingDate;
            
            try
            {

                ax = new Axapta();
                ax.Logon("USMF", "en-us", "TAURUS", null);
                _AxTrainings.Clear();
                using (axRecord = ax.CreateAxaptaRecord(tableName))
                {
                    axRecord.ExecuteStmt("select * from %1 ");
                    
                    while (axRecord.Found)
                    {
                        fieldId = axRecord.get_Field(strId);
                        fieldName = axRecord.get_Field(strName);
                        fieldTrainingDate = axRecord.get_Field(strTrainingDate);
                        objAXTrainings = new AXTrainings();
                        objAXTrainings.Id = fieldId.ToString();
                        objAXTrainings.Name = fieldName.ToString();
                        objAXTrainings.TrainingDate = fieldTrainingDate.ToString();

                        _AxTrainings.Add(objAXTrainings);
                        
                        axRecord.Next();
                    }
                }
                return _AxTrainings;
            }

            catch (Exception e)
            {
                //return e.Message;                
            }
            return _AxTrainings;


        }

To create AxTraining, update the Post method as specified below:

public HttpResponseMessage Post([FromBody]AXTrainings objAXTrainings)
        {
            
            Axapta ax;
            AxaptaRecord axRecord;
            string tableName = "Dev_Trainings";

            if (string.IsNullOrEmpty(objAXTrainings?.Name))
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            // insert record in ax
            try
            {

                ax = new Axapta();
                ax.Logon("USMF", "en-us", "TAURUS", null);
                _AxTrainings.Clear();
                using (axRecord = ax.CreateAxaptaRecord(tableName))
                {

                    axRecord.set_Field("Id", objAXTrainings.Id);
                    axRecord.set_Field("Name", objAXTrainings.Name);
                    axRecord.set_Field("TrainingDate", objAXTrainings.TrainingDate);
                    
                    // Commit the record to the database.
                    axRecord.Insert();
                    
                }
                return Request.CreateResponse(HttpStatusCode.Created, objAXTrainings);
            }
            
            catch (Exception e)
            {
                objAXTrainings = new AXTrainings();
                return Request.CreateResponse(HttpStatusCode.Created, objAXTrainings);
            }
            
        }

Build and run the application and test the post method in Postman as below:

Get Method

Post Method

Get Method after Post

Ref Link:

https://developer.okta.com/blog/2019/03/13/build-rest-api-with-aspnet-web-api

Webhook:

Webhook is a tool which delivers data from one application to another application immediately upon the occurrence of a specified event. Webhook is used to get real time data between two applications.

Wrapping Up

Following all the steps mentioned above will help you create your own ASP .NET application without encountering regular bugs. We hope that the blog was helpful in clarifying everything about the ASP .NET development process. Please feel free to get in touch with our engineers at DEV IT for any persistent issues in the development stage.

The post Step by Step Guide to Create Restful API for Dynamics AX Data appeared first on DEV IT Journal.



This post first appeared on DEV IT Journal - Simplifying IT, Empowering Busine, please read the originial post: here

Share the post

Step by Step Guide to Create Restful API for Dynamics AX Data

×

Subscribe to Dev It Journal - Simplifying It, Empowering Busine

Get updates delivered right to your inbox!

Thank you for your subscription

×