Advancedrestservices v1
Advancedrestservices v1
EDE8507988
90521-10-9276-583101432
10.2.500
Revision: September 02, 2019 11:53 p.m.
Total pages: 26
course.ditaval
Advanced Epicor REST Services Contents
Contents
Introduction............................................................................................................................4
Before You Begin....................................................................................................................5
Audience.........................................................................................................................................................5
Prerequisites....................................................................................................................................................5
Environment Setup..........................................................................................................................................6
Workshop Constraints..............................................................................................................................7
REST Services Data Security...................................................................................................8
Request Authentication and Authorization.......................................................................................................8
Workshop - Obtain Access Token from the TokenResource Service...................................................................9
External API Testing Tools...................................................................................................10
Postman........................................................................................................................................................10
Workshop - Setting Up Postman for Testing Epicor API...........................................................................10
Set Up Testing Environment.............................................................................................................10
Get an Access Token (Optional).......................................................................................................11
Add Request Headers......................................................................................................................11
Workshop - Using Postman for Testing Epicor API...................................................................................12
GET the List of Sales Orders.............................................................................................................12
POST Create a New Customer.........................................................................................................13
PATCH Update a Customer.............................................................................................................13
DELETE a Customer.........................................................................................................................14
cURL..............................................................................................................................................................14
cURL Command Options.........................................................................................................................14
Workshop - Using cURL for Testing Epicor API........................................................................................15
REST-Based Integration with Epicor ERP.............................................................................18
Workshop - Integrating a Web Application with Epicor ERP............................................................................18
Review the User Interface of the Sample Application...............................................................................18
Review the JavaScript Code of the Sample Application............................................................................19
Generate Access Token...........................................................................................................................20
Connect to ERP and Retrieve the List of Customers.................................................................................21
Add/Update a New Customer.................................................................................................................22
Delete a Customer..................................................................................................................................23
Modify REST Request to Sort Customers by Name...................................................................................24
Conclusion.............................................................................................................................25
Introduction
Read this topic for information you should know in order to successfully complete this course.
Audience
Prerequisites
To complete the workshops in this course, the necessary modules must be licensed and operating in your training
environment. For more information on the modules available, contact your Epicor Customer Account Manager.
It is also important you understand the prerequisite knowledge contained in other valuable courses.
• Introduction to Epicor REST Services Course - This course is an introduction to using Representational
State Transfer (REST) services for interaction with Epicor ERP.
• Database Concepts Course - This course reviews the table and field name identification process using Field
Help, Customization Tools, and the Data Dictionary Viewer functionality. It also describes table linking
procedures and requirements as well as join type definitions and specifications.
• Business Activities Queries Course - This course introduces the Business Activity Query (BAQ) Designer
data extraction tool. It discusses data location concepts and provides an overview of query building techniques
using the Query Builder, the Criteria Wizard, and the Calculated Field Wizard.
®
• System Administration Course - This course explores how Microsoft SQL Server interacts with the Epicor
ERP application. Designed for database administrators, this course describes the SQL Server features
administrators manage to run the Epicor ERP application.
• System Setup and Management Course - This course explores how you set up and manage the Epicor
ERP application. By understanding these tools, you control how users access and run the application as well
as manage automatic processes and customizations.
• Technical Knowledge
• Advanced knowledge of the HTTP protocol
• Web (JavaScript) programming skills
• Knowledge of Command Line Interface commands and protocols
• Industry Knowledge - Understanding the functionality of the current release of the Epicor ERP application.
Environment Setup
The environment setup steps and potential workshop constraints must be reviewed in order to successfully
complete the workshops in this course.
Your Epicor training environment, in which the Epicor demonstration database is found, enables you to experience
Epicor functionality in action but does not affect data in your live, production environment.
The following steps must be taken to successfully complete the workshops in this course.
1. Verify the following or ask your system administrator to verify for you:
• Your Epicor training icon (or web address if you are using Epicor Web Access) points to your
Epicor training environment with the Epicor demonstration database installed. Do not complete
the course workshops in your live, production environment.
Note It is recommended that multiple Epicor demonstration databases are installed. Contact
Support or Systems Consulting for billable assistance.
• The Epicor demonstration database is at the same version as the Epicor application. The
demonstration database is installed from the Epicor Administration Console using the "Add Demo
Database" command under Database Server. See Epicor ERP installation guides for details. If you are an
Epicor Cloud ERP customer (and have licensed embedded education), the demonstration database is
installed for you.
• Your system administrator restored (refreshed) the Epicor demonstration database prior to
starting this course. The Epicor demonstration database comes standard with parts, customers, sales
orders, and so on, already defined. If the Epicor demonstration database is shared with multiple users
(that is, the database is located on a server and users access the same data, much like your live, production
environment) and is not periodically refreshed, unexpected results can occur. For example, if a course
workshop requires you to ship a sales order that came standard in the Epicor demonstration database,
but a different user already completed this workshop and the Epicor demonstration database was not
restored (refreshed), then you will not be able to ship the sales order. If you are an Epicor Cloud ERP
customer see section below.
2. Log in to the training environment using the credentials manager/manager. If you are logged in to your
training environment as a different user, from the Options menu, select Change User.
3. From the Main menu, select the company Epicor Education (EPIC06).
Note To refresh your Epicor training data, enter a support ticket in EpicCare and include your site ID.
Workshop Constraints
This topic lists the environment settings required to complete the workshops.
• All workshops require Internet connection in your training environment.
• The workshops that require installation of Postman:
• Workshop - Setting Up Postman for testing Epicor API.
• Workshop - Using Postman for testing Epicor API.
• Workshop - Using cURL for testing Epicor API requires installation of cURL.
• Workshop - Integrating a Web Application with Epicor ERP requires downloading Sample JavaScript
Application Code.
Important The link to the Sample JavaScript Application Code download is available from the web
version of the course only.
For this workshop, the recommended editor is Visual Studio Code, however, you can use any JavaScript editor
you like.
To protect data, each API request should come with some sort of authentication credentials which must be
validated on the Epicor application server for each request.
In the Epicor ERP, REST services data is secured by implementing user authentication and authorization. First, the
user is authenticated against the Epicor ERP. Then the application server applies data access restrictions imposed
on the authenticated user. Therefore, the Epicor REST API provides access to Epicor ERP services in total compliance
with the existing user security model of the queried application server. For example, if an Epicor user does not
have access to a certain ERP module - for example, A
You secure the data that comes from REST by implementing authentication codes. This section describes the
code you enter to secure the data you display through REST services. You then secure the streaming data from
malicious activity.
You should always use the HTTPS protocol with REST services. This protocol is a secure way for REST to transfer
data between the Epicor ERP and a third-party application.
REST API supports 2 authentication methods: Basic and Token. Request authorizations matches the Epicor user
access rights.
You must specify the authentication type in your REST requests by adding the Authorization header.
• Basic authentication (recommended for quick API testing)
The username and password are combined into a string separated by a colon and encoded using Base64. The
result is placed into the Authorization header: Authorization: Basic {encoded string}.
• Token authentication (preferred option for integration scenarios)
In the Epicor ERP, Token Authentication is configured automatically during application server deployment.
Tokens provide an extra level of security for users who log into the Epicor ERP through external applications.
If you activate this security feature, the web services require that a valid token be available when users log
into the application.
Tip If you have issues with automatic token configuration and need to run the process manually. Refer
to the Epicor Administration Console help (Epicor Application Server - <version> > Configure Token
Authentication > Activate Tokens).
Each token only lasts for a short period of time (sometimes, one hour) before it expires. This ensures a new
token is required each time the external user or application accesses the system, preventing malicious entry
into the Epicor ERP application.
The bearer token can be obtained for a user from the token service of the Epicor ERP.
Tip See the service help document at
https://[AppServerHost]/[AppServerInstance]/TokenResource.svc/ help for details on available
operations.
The access token should be sent in the Authorization header in the following format: Authorization: Bearer
{token string}.
This workshop provides the procedure for obtaining access tokens from the Token Resource service of the Epicor
ERP.
While you can program your third-party application to obtain or update an access token prior to each REST
request, which will be further described in the REST-Based Integrations with Epicor ERP section, you can
always get the token manually from the Epicor REST API. Complete this workshop to learn how.
1. Go to https://[AppServerHost]/[AppServerInstance]/TokenResource.svc/
3. For the User name and Password, enter the credentials of the Epicor user for whom you're creating the
token. For example, manager/manager.
Alternately, you can obtain an Access Token by sending a POST request to invoke a GetAccessToken custom
method of Ice.Lib.TokenServiceSvc:
POST /ERP102400/api/v1/Ice.LIB.TokenServiceSvc/GetAccessToken HTTP/1.1
Host: box12.playground.local
Content-Type: application/jsonUsername: managerPassword: manager
Authorization: Basic ZXBpY29yOmVwaWNvcg==
cache-control: no-cache
Postman-Token: 5fc847a1-bd69-49fb-88bc-6ec5520cda6a
{
"clientId": "00000000-0000-0000-0000-000000000000",
"clientSecret": "string",
"scope": "string"
}
This section explains how you can use such API testing tools as Postman or cURL to construct and test the
REST-based interaction of your third-party application with the Epicor ERP.
Postman
Postman is a free tool for API developers to share, test, document and monitor APIs.
The interactive Swagger help page quickly becomes limited when it comes to performing update operations or
doing 'POST' work against custom methods. With Postman, you can construct complex development-level HTTP
requests, or calls. Additionally, the calls can be saved as queries within a larger collection and shared with
co-workers or used as a test suite.
Go to https://getpostman.com to download the free Postman App.
Then complete the following workshops that demonstrate how you can use Postman for testing the Epicor ERP
API.
In Postman, you can add several environments to differentiate between test, development, or production.
Use these steps to set up different environments for testing the Epicor REST API.
1. Launch Postman.
If prior to this you haven't defined any environments, the Current environment drop-down field in the
top right corner of the page is set to No Environment.
2. Click the Environment quick lookup (the "eye") icon next to the Current environment field.
The Manage Environments window displays.
4. Optionally, you can define global and environment-specific variables. Click on an empty line in the variables
grid and add a name for your variable. For example, Host.
5. In the Initial Value field, enter the address of your server and the Epicor appserver name beginning with
protocol. For example, https://box12.playground.local/ERP102400Test.
You can now use this variable in your request URLs in the following format: {{Variable Name}}.
Example Add another environment and define a different value for the same variable - for example,
https://box10.playground.local/ERP102400Dev. The value of a variable in the same HTTP requests
will change depending on the selected environment. So you can easily switch from a testing
environment to development to see how your requests go through.
6. In the Builder section of the Postman screen, select the HTTP method and enter the URL of your request.
For example, {{Host}} /api/v1/Erp.Bo.SalesOrderSvc/List, which will get you the list of sales orders in the
system.
Now proceed to the next step to set up standard headers for the requests.
3. On the Authorization tab, for Authentication Type, select Basic Auth and add Epicor Username and
Password. For example, epicor/epicor.
4. In the Headers, you may specify credentials of the different Epicor user you are creating the token for. To
do this, add two headers per below example table:
KEY VALUE
UserName manager
Password manager
5. Click Send.
Note the response body contains the Access Token information.
Use this token in the next step if you wish to use Token Authentication for your requests.
1. Navigate to the Authorization tab and select the type of authentication for the Epicor user.
Select Basic Auth if you want to use Basic Authentication. Then enter username and password of the Epicor
user on whose behalf you are accessing the application server. For example, epicor/epicor.
Select Bearer Token if you wish to use Token Authentication. In the Token field, enter the Access Token
you received from the ERP TokenResource service. For example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIxNTQ4ODUzNDgzIiwiaWF0IjoiMT
U0ODg0OTg4MyIsImlzcyI6ImVwaWNvciIsImF1ZCI6ImVwaWNvciIsInVzZXJuYW1lIjoiZXBpY
29yIn0.QJAElhgeBGi4tfOLzD4c06Zq0lIZhfVkOwT13i2B8ro
Note When you send the request, Postman will use the values from the Authorization tab to
automatically create a temporary Authorization header.
3. In the Key field, start typing content and select Content-Type from the provided options.
5. Add the Accept header with the application/json value to define the type of content in the response.
You are now able to send your request. Proceed to the next workshop to perform some standard CRUD operations
with Epicor data.
This workshop will walk you though all basic create-read-update-delete (CRUD)operations with Epicor ERP data
using Postman.
Keep the setting from the previous workshop and complete the below steps:
In this step, retrieve the list of sales orders from the Epicor ERP.
Use the settings from the previous Workshop - Setting Up Postman for Testing Epicor API.
1. Make sure you are in the right environment and review the settings of your request:
• The HTTP method is set to GET.
• The Request URL looks similar to this - {{Host}} /api/v1/Erp.Bo.SalesOrderSvc/List.
Note The name of the variable is taken from the example in the previous workshop. You may
give your variables a different name. In this case, the Host variable contains a part of the request
URL specifying the location of the host server and ERP instance name -
irv-box12.playground.local/ERP102400Test/.
2. Click Send.
Note the response Status is 200 OK and the response Body contains data of the sales order list from the
Epicor database in JSON format.
3. Navigate to the Params tab to apply OData parameters to your request to reduce the output payload. For
example, add the following parameters to only display these order fields - Company, OrderNum, OrderDate
- for Addison:
KEY VALUE
$select Company, OrderNum, OrderDate
$filter CustNum eq 9
4. Open the Body tab and insert the following code into it:
{
"Company": "EPIC06",
"CustID": "MYTEST",
"CustNum": 0,
"Name": "My test customer",
"TerritoryID": "US MID"
}
Note In this example, the minimum required fields are sent. You can specify values for any fields of
the Customer service model. For example, you can add "Address1": "1234 Oak Tree Lane" to the
request body.
5. Click Send.
Note that the response status is 201 Created and the response body contains data of the newly created
customer in JSON format.
Tip Write down the Customer Number (CustNum) of the new customer, you will use it in the next
step.
Complete this step to update the information of the previously created new customer.
4. Click Send.
Note the response status is 204 No Content and the response body is empty.
5. GET the customer and check the response body to verify the information has been updated.
For Example, GET {{Host}} /api/v1/Erp.Bo.CustomerSvc/Customers('EPIC06',48).
Note In the request URL, use the CustNum of your new customer.
DELETE a Customer
3. Click Send.
Note the response status is 204 No Content and the response body is empty.
5. Note the response status is 404 Not Found and the error message in the response body reads "Record
Not Found".
cURL
Learn how you can use this tool to test your integrations against Epicor ERP REST API.
cURL is used in command lines or scripts to transfer data. It support about 22 protocols including HTTP. This
combination makes it a very good ad-hoc tool for testing Epicor REST services.
curl provides a generic, language-agnostic way to demonstrate HTTP requests and responses. You can see the
format of the request, including any headers and other parameters. You can also translate this into the specific
format for the language used in the application being integrated.
The following workshop demonstrates how you can use curl to perform basic CRUD operations with Epicor ERP
REST services.
This section describes basic cURL command options that can be used for interaction with Epicor ERP REST services.
Options start with one or two dashes. Many of the options require an additional value next to them.
The short single-dash form of the options - for example, -d - may be used with or without a space between it
and its value, although a space is a recommended separator. The long double-dash form - for example, --data
- requires a space between it and its value.
The full list of cURL command options is available in the Options section of this official curl page.
Complete this workshop to walk through basic cURL functionality that may be applied to testing the Epicor ERP
REST API in various integration scenarios.
Important This workshop uses this URL - https://box12.playground.local/ERP102400/ - for the purpose
of demonstration. Replace this URL with the URL of the Epicor application server you are querying.
1. Enter the following command to create an Access Token if you wish to use Token Authentication for your
requests. Otherwise use the -u option for Basic Authentication.
curl -X POST -u epicor:epicor -H 'Accept: application/json' -H 'Content-Len
gth: 0' 'https://box12.playground.local/erp102400/TokenResource.svc/'
Tip Copy the token value from the response.
In this section, you will walk through the process of integrating a JavaScript application with the Epicor ERP using
REST.
The Epicor REST API uses HTTP GET, POST, and PATCH methods to send and receive data in JSON format, so it
is very simple to build client applications using the tool or the language of your choice. This course will focus on
the scenario for integration of a sample web application with the Epicor ERP application server where data will
be exchanged via HTTP requests against the Epicor REST API.
Complete the workshop to get a hands-on integration experience.
Walk through the process of integrating a web application with the Epicor ERP.
Download the Sample JavaScript Application Code zip folder attached to this workshop. Extract the files and
add code to the provided template of the sample Strategic Customer Management application to enable its
interaction with the Epicor ERP. Use the full code of the same application from the second folder to see what
the code elements discussed at different steps of the workshop should look like.
The JavaScript application that you will finalize during this workshop will allow you to handle the ERP customer
service data across different platforms in an easy and secure manner. You will be able to retrieve customer records
with selected customer data, as well as add, update, and delete customer records stored in the Epicor ERP. It will
also provide a check-box control for an additional attribute that will single out strategic customers. Lists of all
customers and strategic customers will be also displayed in the UI.
Download and review the code of the sample application template, add code that will enable this application to
send HTTP requests to an Epicor ERP application server and finally try to further modify HTTP requests for better
usability.
During this step, review the user interface (UI) of the sample web application.
1. Extract the contents of the downloaded zip file and work in the 1 Web App Integration - JS App Template
folder. Note that it contains the html file for your application, as well as these three folders:
• assets - contains an image file with the Epicor logo
• src - contains the template for your JavaScript application (app.js)
• styles - contains stylesheets used in the application
2. Add the root folder of the application to the IIS sites, and run the index.html file in a browser - this workshop
uses Chrome.
Note that the application interface has two tabs: Connection and Strategic Management.
It is used for testing the connection to the Epicor ERP application server by sending a GET request to retrieve
the list of customers from the Epicor database. Note the fields on the form:
• Application Server - specifies the path to the Epicor server, - for example,
https://irv-euvmguest12.playground.local.
• Application name - specifies the Epicor application server instance name - for example, ERP102400.
• Epicor User and Epicor Password - specify the credentials of the acting Epicor user.
• Epicor Token (Optional) - specifies the Access Token obtained from the Epicor TokenResourceSvc.
Note This application will prioritize token authentication over basic. This means that if the Epicor
Token field is not blank, the application will use the value of the bearer token regardless of the
values provided in the Epicor Username and Epicor Password fields.
• Test Connection - when you add code to this button, it will trigger the GET request that will retrieve
customer lists from the Epicor database.
• Generate Token - when you add code to this button, it will send a POST request to the Token Resource
service to create an Access Token for the specified Epicor user.
4. Navigate to the Strategic Management tab. It contains the user interface (UI) controls for standard CRUD
operations with customers. It also displays all and strategic customer lists retrieved from the Epicor ERP:
• ID - specifies Cusotmer ID (CustID).
• Name - specifies Customer Name (Name).
• City - specifies the City from Customer address (City).
• Strategic Customer - use this option to add an attribute that will make a customer 'strategic'.
• New Customer - this button enables editing of new customer data fields.
Note If you had previous customer data in the fields, the button function will erase it.
• Commit Changes - when you add code to this button, it will send a POST (for a new customer) or a
PATCH (for an existing customer) request to the Epicor REST API to create or update customer data in
the Epicor database.
• Delete Customer - when you add code to this button, it will send a DELETE request to remove customer
data from the Epicor database.
• Strategic Customers - this panel contains the list of 'strategic' customers.
• All Customers - this panel contains the list of all customers in the Epicor database.
Proceed to the next step to analyze the JavaScript code of the template application.
In this step, review the template code that you will build upon to enable the app integration with the Epicor ERP.
1. In Visual Studio Code, open the Web App Integration - JS App Template folder by clicking File > Open
Folder.
2. In the Explorer panel, navigate to the src directory and open the app.js file.
Note some important blocks of code.
3. Locate the var _config variable that contains data that is submitted on the Connection tab to connect to
the Epicor REST API.
4. Locate the showToastmessage() function that will display toast messages in response to user actions.
5. Find the validateConnection() function that ensures the connection information entered on the Connection
tab is complete.
6. Locate the getRestRequest() function and see that it is a constructor for any REST call where method
(GET, POST, PATCH, DELETE, etc), servicePath (for example, /Erp.Bo.CustomerSvc/Customers), and data
(stringify(data)) are the parameters.
Note This function uses data from the _config variable, so users need to provide this data on the
Connection tab prior to sending any REST request to the Epicor ERP application server.
In this step, add code to generate an Access Token for the token authentication.
1. Locate the obj.onClickGenerateToken = function(showToast) object and add this code inside the curly
brackets:
var data = `{
"clientId": "00000000-0000-0000-0000-000000000000",
"clientSecret": "string",
"scope": "string"
}`;
// Generate and obtain the token from the Token Resource service
getRestRequest('POST', "Ice.Lib.TokenServiceSvc/GetAccessToken", data)
.done(function (response) {
2. Save your changes to the app.js and refresh the application to test the added functionality.
5. Copy and save this value. You will use it in the next step when you enable testing the connection to the
Epicor ERP.
Test the connection to the Epicor ERP application server by sending a GET request to retrieve the list of customers
form the Epicor database.
The information you need to enter on the Connection tab includes application server URL, ERP application name,
Epicor username and password, and token (optional). The entered data is processed by the onClickTestConnection
function.
1. Locate obj.onClickTestConnection = function(showToast) and add this code to it inside its curly brackets:
// Refresh the list of customers in the second tab
getRestRequest('GET', "/Erp.Bo.CustomerSvc/List?$filter=Company eq 'EPIC06'
&$select=CustNum,CustID,Name,City,PhoneNum&$orderby=CustID Asc", null)
.done(function (response) {
1. The function sends a REST request to retrieve customers from Epicor ERP. In this case the URL
of the request is this:
https://[EpicorAppServer]/[AppServerInstance]/Erp.BO.CustomerSvc/List?$filter=Company
eq 'EPIC06'&$select=CustNum,CustID,Name,City,PhoneNum.
4. The refreshList function is called to update customer lists displayed on the Strategic
Management tab.
2. Save your changes to the app.js and refresh the web application.
3. On the Connection tab of the web application, fill out the form including the previously copied token value.
Note You can generate a new token if you wish.
Add logic to send either a POST request to add or PATCH request to update a customer in the Epicor database.
After you have established connection to the Epicor server, you may enable your application to add, update, or
delete customers in the actual Epicor database using REST requests. In the template, you will find functions
corresponding to different actions that can be performed with customer records. You will now add definition to
the Submit Changes action.
1. In the app.js file, locate onClickCommitChanges and insert the below code in between its curly brackets:
//a. Create a partial new customer object
var data = JSON.stringify({
'CustNum': $('#iCustNum').val(),
'CustID': $('#iCustID').val(),
'Name': $('#iCustName').val(),
'City': $('#iCity').val(),
'PhoneNum': ($('#iStrategic').is(':checked')) ? "StrategicCustomer" : "
"
});
//b. Send a PATCH request for an existing customer or a POST to create new
getRestRequest(($('#iCustNum').val() > 0) ? 'PATCH' : 'POST', requestAddres
s, data)
.done(function (response) {
4. Send request to display the updated list of customers on the Strategic Management tab.
5. Unpack JSON response from the Epicor ERP into user-friendly HTML output.
3. On the Strategic Management tab, add data for a new customer and click Submit Changes.
The Customer Updated message displays and the new customer appears in the All Customers list.
Note If you select the Strategic Customer option, the new or updated customer will appear in the
Strategic Customers list.
4. Now for the newly created customer, change the City and click Submit Changes.
The Customer Updated message displays and the customer data contains a different city name now.
Delete a Customer
Add code that will send a DELETE request to remove a customer from the Epicor database.
1. In the app.js, locate obj.onClickDeleteCustomer = function() and insert the below code inside its curly
brackets:
//a. Send a DELETE request to the Epicor ERP
getRestRequest('DELETE', "/Erp.Bo.CustomerSvc/Customers('EPIC06'," + $('#iC
ustNum').val() + ")", null)
.done(function (response) {
//d. Fail is called when the rest request fails for some reason
console.log('Can not delete a customer - ' + errorThrown);
showToastmessage('Can not delete a customer - ' + textStatus, 2);
});
Note
3. Select your new and later updated customer from the list.
Use additional OData parameters in the REST requests to improve usability of the application.
Note that the list of customers in the web application is sorted by Customer Number (CustNum). Use additional
OData parameters in REST requests to sort the list in alphabetical order by Name.
Add an orderby parameter to the GET request that retrieves the list of customers from the Epicor ERP.
Conclusion