D365 Business Central - How to update Currency Exchange Rate through External API
In Business Central we can be able to consume the external API’s and based on API Response we can update the Response result into the tables as per our Requirement.
As per my requirement, while modification in the Currency Table, if there is no record in “Currency Exchange Rate” Table then we need to call the external API and that API will fetch the latest (Real-time) exchange rate from the server and provide the response. Accordingly based on the response we need to update “Currency Exchange Rate” Table.
In this example we will discuss how we can insert the record into “Currency Exchange Rate” Table while modification in “Currency”.
Step 1: Firstly, we need to create New Table with 3 Fields, Like “Primary Key”, URL and Blob.
Step 2: Then we will create new codeunit that will call the external API and Fetch the latest exchange rate. In this codeunit I have defined Function DoFetchExchangeRate() and inside that we have InitArguments, FetchExchangeRate and ViewResult functions. With the help of these functions, we will call the external API and Fetch the response from http://api.exchangeratesapi.io/v1/latest?access_key*****. You need to get the access key through signup on http://api.exchangeratesapi.io.
Step 3: We have added the below logic in CallRESTWebService() function to send the API request and get the API Response.
Step 4: Now we have a logic ready that will call the external API and that API will fetch the real time exchange rate from the server. Next, we have to update the “Currency Exchange Rate” table if there is no record in the table while modification of Currency. For this we need to write the logic on OnAfterModifyEvent and need to update the “Currency Exchange Rate” table. I have added the code below to update the response received from API and update the same into “Currency Exchange Rate” table.
Step 5: Now I will go to the business central web client and verify this. I will Go to Currencies and then Currency Exchange Rate. In this example I will check this for AUD Currency. You can see now there is no record in “Currency Exchange Rate” Table for AUD Currency.
Step 6: Now I will modify the currency and “Currency Exchange Rate “should be updated for AUD Currency based on the API Response.
You can see now the “Currency Exchange Rate “ is updated from the API Response.
This will be helpful for those who want to call the external API in business Central and parse the Response.
Thanks & Regards,
Naveen Gour
*This post is locked for comments