If you find any errors, typos or have general feedback, select the text and click CTRL+ALT+ENTER.

Introduction

API Express makes it easy to expose external data source via REST APIs. Once the data sources are exposed, you can easily build a mobile app with those APIs and in turn with the external data sources.

The following external data sources are supported:

  • Relational database
  • SOAP (Web service)
  • REST API

There are two main options to create a REST API in API Express:

  • Automatically generate a REST API
    • This option works with relational databases
  • Use a visual service builder to create advanced service logic

The visual service builder has the following components to build service logic:

  • SQL component – for executing any SQL query or stored procedure.
  • REST component – for connecting to any external REST API.
  • SOAP component – for connecting to a SOAP web service.
  • FORK component – for creating two or more execution forks.
  • Condition – for adding if-else-like condition.
  • Mapping – for mapping data from one component to another.
  • Script – for adding custom logic using JavaScript.
  • Server Code – for invoking an Appery.io Server Code script.

Tutorials

Here you will find step-by-step tutorials for using API Express to expose external data sources via APis.

  • Your first API Express tutorial.
    This tutorial shows how to connect to a relational database in the cloud, expose it via REST APIs and build a simple mobile app to consume the API.

Once you tried the first tutorial, you can try these more advanced tutorials:

Working with a database

This section covers how to create a database connection.

You can find a guide on how to integrate Microsoft Azure and Google SQL into API Express here.

Before you can start working with your API Express projects, you must create a database connection.

From the Builder, open the API Express view, and click Create new DB connection.

When creating a new database connection, select between relational and Appery.io databases.

Creating relational database connection

To create a new relational database connection, click Create new DB connection, select Relational database for Connection type, enter the required credentials, and click Save.

To get the required credentials, check with your database service. For example, for HostBuddy, you can find the credentials under the MySQL Manager tab on the Hosting Control Panel:HostBuddy

The following database types are supported: SQL Server, Oracle, PostgreSQL, and MySQL.

Configurations of the Database schema while creating/updating database connections depend on the database type:

  • SQL Server – the predefined dbo schema is passed by default.
  • Oracle – there is no default schema and passing it is optional.
  • Postgre SQL – the predefined public schema is passed by default.
  • MySQL – the field is disabled and no schema is required.

To enhance the performance of executing commands on a database, configure caching your database connections in the Pool Settings section:

The following values are recommended for Pool Settings:

Max active – between 1 to 9.
Max idle – between 1 to 9.
Max wait – between 1 to 10000.

To ensure you enter valid data, click Test.

Creating Appery.io database connection (cloud only)

API Express (when used with Appery,io, not installed as standalone) allows to build offline apps with your external database connected. It’s also possible with Appery.io database.

To use this option, go to the API EXPRESS tab and create a new database connection with Database type = Appery.io database.

Then, from the drop-down, select the needed database and enter the other credentials:
NewDBConnectionAppery

If your API Express project is not secured, the credentials provided in the form will be used to login and access the Appery.io database.

If you secure your project by checking the Allow only authenticated users to call REST box (check this section for more information), the credentials provided to API Express will be used to connect to your Appery.io database.

To ensure you enter valid data, click Test.

It is essential that you create a model to enable offline support. To create one, follow these instructions.

Making your relational database available for API Express

We suggest using your own databases for the Appery.io API Express service. However, it’s important that you understand how to configure the database you will use in your project.

If you use a real/white IP address on your database server, write down this address in the Host field. Also, you can use a DNS (Domain Name Service) record for your database server. Be positive that your firewall is properly configured and allowed internal connections to your database server from Appery.io. Our application servers DNS are:

  • aex1.appery.io
  • aex2.appery.io
  • app5.appery.io
  • app6.appery.io

If you’re using PostgreSQL, you should also properly configure the allowed host in the pg_hba.conf file.

In some cases you’ll have to provide IP address instead of domain names. For example. You can execute the nslookup command to see the actual IP addresses, for example:

or

If you use a hidden/internal/gray IP address on your database server, you should make additional settings for using your own database. You can ask your ISP (Internet Service Provider) to realize a real IP for your database server or configure port forwarding. For example, if using gateway (GW) with Red Hat/CentOS and IP MASQUERADE configured, for PostgreSQL port forwarding (standard port 5432), you should run the following commands:

If using other OS/Devices as a GW, please use the appropriate manual.

If you have any questions, please contact us at support@appery.io.

Supported relational databases

Here’s the list of supported relational databases and data types:

MySQL SQL Server Oracle PostgreSQL
BIT
TINYINT
BOOLEAN
SMALLINT
MEDIUMINT
INT
BIGINT
FLOAT
DOUBLE
DATE
DATETIME
TIMESTAMP
CHAR
VARCHAR
TINYBLOB
TINYTEXT
BLOB
TEXT
MEDIUMBLOB
MEDIUMTEXT
LONGBLOB
LONGTEXT
SET
TINYINT
SAMLLINT
INT
NUMERIC
DECIMAL
SMALLMONEY
MONEY
REAL
BIT
CHAR
VARCHAR
NCHAR
NVCHAR
TEXT
IMAGE
DATETIME
SMALLDATETIME
NUMBER
SMALLINT
DOUBLE
CHAR
INT
DEC
NUMERIC
REAL
DECIMAL
VARCHAR2
VARCHAR
FLOAT
TIMESTAM
CLOB
BLOB
DATE
INT8
SMALLINT
TEXT
BOOLEAN
TIMESTAMP
SMALLSERIAL
BIGINT
DATE
BIGSERIAL
INTEGER
TIME
LONG
SERIAL
NUMERIC
DOUBLE_PRECISION
CHARACTER
REAL
CHARACTER_VARYING
VARCHAR

Appery.io offers predefined REST connections users may link to their database and, therefore, generate models for specific tables from their database (each model having a set of connected REST services).

Users can also include clientsdk.js (static lib from API Express host that contains base host setting where to route REST calls).

Exposing your external data source

Before you can start working with API Express, you must expose your remote data source to API Express.

Making your web services available for API Express

It’s important that you understand how to configure your external data source you will use in the API Express.

If you use a real/white IP address on your server, you will use external data source URL. Also, you can use a DNS (Domain Name Service) record for your external data source server. Ensure that your firewall is properly configured and allowed internal connections to your server from Appery.io. Our application servers DNS are:

  • aex1.appery.io
  • aex2.appery.io
  • app5.appery.io
  • app6.appery.io

In some cases you’ll have to provide IP address instead of domain names. For example, you can execute the nslookup command-line tool (Windows, Linux, Mac OS X) or whois-like services from the Internet (like ping.eu, etc) to see the actual IP addresses:

or

If you use a hidden/internal/gray IP address on your server, you should make additional settings for using your own server. You can ask your ISP (Internet Service Provider) to expose a real IP for your server or configure port forwarding. For example, if using a gateway with Red Hat/CentOS and IP MASQUERADE configured, for server port forwarding (standard port 443), you should run the following commands:

If using other OS/Devices as a gateway, please prefer to its documentation.

If you have any questions, please contact us at support@appery.io.

Supported protocols

Here’s the list of supported web services and protocols:

Service Protocols and their versions
SOAP
  • HTTP (HTTPS) 1.0 and 1.1
  • WSDL 1.0 and 1.1
  • SOAP 1.1 and 1.2
  • XML 1.0
REST
  • HTTP (HTTPS) 1.0 and 1.1
  • JSON

Working with a project

In order to create a new REST API, you first need to create an API Express project. A project holds one or more REST APIs.

1. Open the API Express page, click Create new project, and enter the required credentials.

2. You can open, edit or delete the project by clicking the corresponding buttons.

3. After you click Open, the next view opens. It has three tabs: API, Settings and Permissions:
Project

Working with a folder

Inside a project you can create one or more folders. A folder allows to organize your APIs. The folder name will be part of the RES API endpoint name.

Under the API tab, you can build the folder and model hierarchy. The REST services URL will be constructed based on folder hierarchy.

1. Click new folder, enter the name and its description, then click Create.

2. To create a subfolder to the API Express folder, click the new folder link located next to the folder’s name, and repeat the procedure.

3. To edit or delete folders, use the the edit and delete links correspondingly.

Multiple models can be created on the same project, each of which relating different sets of data and involving different users.

Importing an API Express project

In API Express tab, click Create new project and choose a project backup file on your computer under the Import from backup section.

Exporting an API Express project

To create a project backup, open your API Express project Settings tab and click Export Backup:
Export_backup

Generating a REST API (Model)

Before creating a model, make sure your table contains the primary key (there may be only one).

1. To generate a new model, click new service. Then select Generate REST API.

2. Enter the model’s name and its description; then, from the drop-down menu, select the database connection and then select the table from the newly opened dropdown combobox of the preloaded tables.

3. If needed, modify the actions (check/uncheck) to be applied to the database data (FIND, GET, CREATE, UPDATE, DELETE).

4. By default, the model and the table have the same name. To edit the model’s name, click edit and enter a new name.

The Key parameter is assigned by the system automatically and can’t be reassigned. It can’t be excluded from the model either.

By checking/unchecking the Include box, you’ll include/exclude the rest of the parameter to/from the model.

Check Sort for the the particular table field to enable sorting by this field (by default, sorting by id field is enabled); then select the order of sorting: asc (ascending) or desc (descending):

5. After you define all the necessary model data and click Save, the project API tab opens. This view shows the folders and models on the project. It also allows editing or deleting them.

To collapse or expand folders or models, click the corresponding folder icon. To return to the previous view, click Cancel.

Testing a REST API

To test the created model, open test view by clicking the test link.

If the Allow only authenticated users to call REST box is checked (on the Settings tab), entering session token is required for testing. To learn how API Express security works, check this section.

Now, click the corresponding tab to select the REST service – FIND, GET, CREATE, UPDATE, or DELETE.

Let’s create a new item and test the model:

1. Select the CREATE tab, enter the parameters into the Request payload field, and click Test:

Now, when you switch to the GET tab and enter the ID of the created entry, the system will retrieve it in the test:

The tabs UPDATE and DELETE perform similarly.

Under the FIND tab, to refine the results, define the offset and the limit parameters (if needed) and leave the Request payload field empty.

For example, offset = 1, limit = 2, the count box checked:

With the count checkbox checked, getting the record count on the database is enabled.

Keep in mind, that the REST Service response can’t exceed the limit of 10241000B and the number of entries in one response can’t exceed 100.

The number of records that can be returned equals 1000.

Unless otherwise specified by a user, the default query size is set to 100.

Comparison query operators

API Express models Find operation can be invoked with the following parameters.

Here is the comparison order:

  • $eq – Matches values that are equal to a specified value.
  • $gt – Matches values that are greater than a specified value.
  • $gte – Matches values that are greater than or equal to a specified value.
  • $lt – Matches values that are less than a specified value.
  • $lte – Matches values that are less than or equal to a specified value.
  • $ne – Matches all values that are not equal to a specified value.
  • $in – Matches any of the values specified in an array.
  • $nin – Matches none of the values specified in an array.

E.g. you can use this expression:

This is the same as:

Similarly, use the following:

This means:

Debug mode

Checking the Debug mode checkbox under the project Settings tab enables the option of displaying response to the user making requests to relational databases with API Express.

No debug mode notifications are sent when a user makes changes to Appery.io databases.

Below is the detailed error notification (in addition to the generic error response) the user will get after making changes to the username (or password) in Database connection view and having the debug mode activated:

Creating a REST API with visual service builder

The visual service builder allows you to create an advanced service flow. The visual service builder provides the following components:

The visual service builder has the following components to build service logic:

  • SQL component – for executing any SQL query or stored procedure.
  • REST component – for connecting to any external REST API.
  • SOAP component – for connecting to a SOAP web service.
  • FORK component – for creating two or more execution forks.
  • Condition – for adding if-else-like condition.
  • Mapping – for mapping data from one component to another.
  • Script – for adding custom logic using JavaScript.
  • Server Code – for invoking an Appery.io Server Code script.

You can define any custom service flow logic by drag and dropping components into the flow.

 

A flow is restricted to 50 components in total (including branches, merges, start and stop components – that means all nodes in a graph).

Service components data

There are objects that can be accessed from certain components during a service execution:

  • BODY – contains the output body from previous component. For example, you have a following scheme: START > REST > Mapping > END. Accessing this parameter in the Mapping component will return data, that was retrieved by a REST component.
  • SESSION – an object that contains authentication session data.This will be empty if the project is not secured. See here on how to secure projects.
    • USER_NAME –  the name of the authenticated user. This will be null if the project is not secured.
  • PARAMS – the object that contains parameters is initially passed by the user and other information provided by API Express.
    • PATH – an object contains all parameters passed as PATH PARAMETERS.
    • QUERY – an object contains all parameters passed as QUERY PARAMETERS.
    • HEADER – an object contains all parameters passed as HEADER PARAMETERS.
    • BODY – contains a service request body (if POST or PUT methods are used).

Start component

The Start component is the entry into the service flow. The Start component defines the endpoint for the REST API in Properties.

With the Start component selected, under PROPERTIES, you can specify the following parameters:
Start_component

  • The relative path of the service (the prospective path parameters are parsed automatically).

    If you change a name of path parameter its type will be reset to default.

  • HTTP method (GET, POST, PUT, DELETE).
  • The optional description.
  • Path parameters with their type defined (string, number, or boolean).
  • Query parameters and their types (string, number, or boolean).
  • Headers and their types.
  • Message body and its type (JSON or String).

SQL Component

SQL

The SQL component allows to execute any SQL query. Read more about database connections here.

For the SQL component, the following can be specified:

  • Database connection.
  • SQL query.
  • SQL parameters and their mapping (click Parse SQL parameters to map the SQL parameters to parameters which can get into this component).
  • Response JSON (response body) that can be generated.

The sample SQL component:
SQL_component

To generate a response JSON, click Generate and, in the Test SQL view, define the SQL parameters field, then click Run SQL to get the response JSON:
TestSQL

The following databases are supported:

  • PostgreSQL (supported versions from 7.2 to 9.3)
  • Microsoft SQL Server (supported versions 6.5, 7, 2000, 2005, 2008 and 2012)
  • Oracle Database (supported versions 11.1.0, 11.2.0.x and 12.1.0.x)
  • MySQL (supported versions 4.1, 5.0, 5.1, 5.5, 5.6, 5.7)

REST component

The REST component allows to connect to any external REST API.

The REST component has the following properties:

  • The absolute path to the service (the prospective path parameters are parsed automatically).
  • HTTP method (GET, POST, PUT, DELETE).
  • Request JSON (request body) (to be defined if the HTTP method is POST or PUT).
  • Path parameters and their mapping.
  • Query parameters and their mapping.
  • Header parameters.
  • Response body JSON that can be generated.

If you change a name of path parameter its mapping will be reset to default.

A sample REST component:
REST_component

To generate a response JSON, click Generate and, in the pop-up window, define Path parameters and Header parameters fields, then click Run REST to get the response JSON:
TestREST

HTTP (HTTPS) 1.0 and 1.1 are supported.

Examples

This section shows a number of examples using the REST component.

Connecting to spelling REST API

This example shows how to use a REST service that checks spelling and suggests a correct word.

  1. Select the Start component (top circle). Set URI templatespelling, HTTP method = PUT.
  2. Select Body type = String and enter the following body (here ‘textt’ is misspelled intentionally):
  3. Drag and drop the Script component into the flow. Enter the following script code:
  4. Click Run script and see this result:
  5. Drag and drop the REST component into the flow and enter this URL http://speller.yandex.net/services/spellservice.json/checkText for URL in Properties.
  6. Select HTTP method = POST and Content-Type = 'application/x-www-form-urlencoded'.
  7. Use this request body:
  8. Click Generate to configure this service.
  9. Here enter the following request:
  10. In Content-Type leave 'application/x-www-form-urlencoded' and click Run REST API.
  11. See the following response structure:
    Here s is a suggestion of correct spelling.
  12. Click Import response.
  13. Select End component. Set Content-Type = text/plain and Response mappingBODY.BODY[0].s[0] to display a suggested spelling.
  14. Click Save.
  15. You are now ready to test the service. Click Test to test the service.

Video example – connecting to external REST API

This video example shows how to connect to an external REST API service from the API Express.

SOAP component

The SOAP component allows you to connect to an existing WSDL service. This allows you to expose the service as REST API or use the component data in service flow for more advanced service logic.

The SOAP component has the following properties:

  • WSDL URL – URL to service’s WSDL (description). This type of URL usually ends in ?WSDL.
  • Service – service available from the above entered URL.
  • Port – ports available for the above selected service.
  • Operation – operations available for above selected service.
  • Header parameters – any header parameter to be included in the SOAP request.
  • Body – service request body
    • Request parameters can be inserted using: ' + PARAMS.QUERY.param_name + '
    • Request field length is limited to 10000 characters, and execution time is restricted to 3 seconds.
  • Response – service response (automatically populated)

The following protocols are also supported:

  • WSDL 1.0 and 1.1
  • SOAP 1.1 and 1.2

Examples

This section shows examples how to use the SOAP component.

Example – passing parameters

This example shows how to use a SOAP service that takes one input parameter. This service converts temperature from Fahrenheit to Celsius and Celsius to Fahrenheit.

  1. Drag and drop the SOAP component into the flow. The flow should consist of Start, SOAP and End components.
  2. Select the SOAP component and enter this URL http://www.w3schools.com/xml/tempconvert.asmx?WSDL for WSDL URL in Properties.
  3. Click Retrieve to configure this service.
  4. After a few seconds, open the Service list and select TempConvert.
  5. For Port select TempConvertSoap12 option.
  6. For Operation select FahrenheitToCelsius. Once you make this selection the request will be automatically populated.
  7. In the request input, scroll through the response until you see this line:
  8. Replace the ? with ' + PARAMS.QUERY.temperature + '. It should look like this:
  9. Select the Start component (top circle).
  10. For URI template enter tempconvert.
  11. With the Start component still selected, under the QUERY PARAMETERS section, add a temperature parameter of the String type.
  12. Click Save.
  13. You are now ready to test the service. Click Test to test the service.

More information on the SOAP component on our blog.

Example – Basic Authentication

When a SOAP services is secured with Basic Authentication, here is how to use it in API Express:

  1. Create an administrator user in Users collection (Appery.io database)
  2. Upload your WSDL file into the Files collection.
  3. Specify that only administrator user can have access to this file (via ACL).
  4. Use the Master Key in WSDL URL for SOAP component
    • The URL will look like this: https://api.appery.io/rest/1/db/files/5617c3d1e4b01d89fb7656d9/5406f5d0......7a6bb.soap.wsdl?masterKey=<your_master_key>
  5. Add authentication header for SOAP request with “username:password” string in Base64 format.
    • Header parameter name: Authorization
    • Header parameter value: Basic <base64_string>
      For example “user1:pass1” is “dXNlcjE6cGFzczE=” in Base64. You can use an online tool such as https://www.base64encode.org/ to create the string or use the browser console to invoke this JavaScript: window.btoa("user1:pass1");
  6. You are now ready to test and run the service.

Example – video

This video example shows how to connect to an external SOAP service from the API Express.

Fork component

FORK

The Fork component allows to execute two more execution branches at the same time.

  • Branches can be renamed.
  • Merge element is a converter that provides the automatically generated response JSON from all branches.

Select the component and click + to add a new branch. And, conversely, to delete the branch (or any other component in the diagram), select it, click x and confirm:
PlusMinusBranch

For the Fork component, the timeout is set (if the connection takes more that the timespan defined, the timeout is returned to the user and the user doesn’t have to wait longer than specified).

Fork component is restricted to 10 branches in total.

Condition component

CONDITION

The default Condition component contains two Branches (Case1 and else) with placeholders and a Merge element:

  • Branches can be renamed and all conditions must be added.
  • Merge element is a converter that provides the automatically generated response JSON from all branches.

Select the Condition component and click + to add a new branch:
Condition_component

Select the needed branch and click Edit to open a Condition Builder. Add logical expressions, and the code will be generated automatically:
Condition_builder

Use groups to unite conditions in braces:
Condition_builder_groups

Merge takes JSONs in different formats and generates a code that checks which branch is executed.

Here is the sample generated code. You can edit it as you need:

Condition component is restricted to 10 branches in total (including else branch).

JavaScript code length is restricted to 1000 characters and script execution time is restricted to 3 seconds.

ECMAScript 5, JavaScript 1.7 + generator expressions are supported.

Examples

This section shows examples how to use the Condition component.

Example – video

How to Design Advanced API Logic Flow With the Condition Component in API Express

Mapping component

Mapping

The Mapping component converts one JSON structure into another:
Mapping_component

Enter response JSON and click Generate mapping to open the Mapping editor. Then using drag and drop you are able to map the parameters to the response:
Mapping_editor

Click Save and Replace and the appropriate JavaScript code will be generated:
Mapping_component_result

You can edit the generated JavaScript code as needed.

ECMAScript 5, JavaScript 1.7 + generator expressions are supported.

Script component

Script

The Script component complements the service flow with data transformations and calculations. It can be used for changing the body structure before passing data to another component. For example, using a script to transform requests from String to JSON, so that you can perform mathematical calculations with input data and to provide output result.

The Script component can access request/session data. For creating more complex scripts use ServerCode component.

Examples

This section shows examples how to use the Script component.

Example – Calculations

This example shows you how to use a Script that takes one input parameter and performs data calculations.

  1. Drag and drop the Script component into the flow. The flow should consist of a Start, Script and End components.
  2. Select the Start component, add a request query parameter someParameter of type Number, and set HTTP method = POST in Properties.
  3. In the request body, enter the following structure:
  4. Select the Script component. You can see the read only JSON structure received from the Start component.
  5. Enter the following script code:
    In the code above, BODY.data values summed up with PARAMS.QUERY.someParameter value and this sum then divided by 2. In the same manner you can access all available objects and their parameters. Example with PATH parameter:
  6. Click Run Script to evaluate the script.
  7. The following script results can be seen as the component output:

ECMAScript 5, JavaScript 1.7 + generator expressions are supported.

Example – Video

This video example shows how to use the Script component to process a response from a REST API (REST component).

Server Code component

ServerCode

The Server Code component allows you to call Server Code scripts from the API Express.

Examples

This section shows examples how to use the Script component.

Example – video

This video example shows how to use the Server Code component to invoke an existing script. The Server Code script does a multi-object database update.

Example – Invoking a simple script

This example shows how to run a Server Code script using the Server Code component.

Here is how you create a Server Code script that returns certain parameters.

  1. Go to Server Code and create a new script, name this script universalScript.
  2. Enter the following script code:
  3. In Script parameters tab, select request method POST and add the following request parameters:
    param1 : 001
    param2 : 002
    param3 : 003
  4. Select MIME type JSON and enter the following request body:
  5. Click Save.
  6. To test the script, open the Run tab and click Save and run. The script returns path parameters, parses body as JSON and returns parameter ok = 1:

Here is how to use this integration feature.

  1. Go to API Express, open or create a project and create a new service.
  2. Select Start component. In PROPERTIES set URI templateuniversalScript/{param1}.
  3. Select HTTP method = POST, add a query parameter param2 of type Number and a header parameter param3 of type Boolean.
  4. Drag and drop the ServerCode component into the flow. Choose existing Server Code script named universalScript from the list of server code scripts.
  5. Select HTTP method = POST, select the following script query parameters:
    param1 = PARAMS.PATH.param1
    param2 = PARAMS.QUERY.param2
    param3PARAMS.HEADER['param3']
  6. For script header parameters, set Content-Type'application/json'.
  7. To send the same body untouched use this script body structure:
  8. Click Generate to test the integration and generate the response. Enter some valid test data and click Run Server Code API.
  9. The response will be generated. Click Import response.
  10. Click Save. The service is ready.

To secure the script, go to Server Code > Script > User management, select a database for managing user access and tick “Allow only authenticated users to call this script”.Then open API Express project > Settings, tick “Secure REST API” and select the same database as a Security provider. From now, you would need to authenticate to database and provide a session token to test the created service.

End

When you have selected the End component which is found under PROPERTIES, you can specify the following parameters:

  • Header parameters.
  • Response body.

Testing REST services

To test the created REST service, open the following view by clicking the corresponding Test tab.

Enter the required credentials (session token, path/query parameters), then click Test:
TestCustomService3

If the Allow only authenticated users to call REST box is checked (on the Settings tab), entering a session token is required. To learn how API Express security works, check this section.

Testing the service with the empty body field in Request payload produces the full list of the entities on the database:

Of the REST Service types, only POST and PUT work with passing body JSON under the corresponding tab.

Security

Proceed to the Permissions tab where permission rights to your projects can be defined.

To get access to the resources on the team project, the user must be on the team. Find more about managing permissions for teammates here.

The API key is found under the API EXPRESS > Settings tab. By checking the Allow only authenticated users to call REST box, you’ll get access to the security providers drop-down menu.

In securing their projects Appery.io users have several options to select from:

  1. Authenticating with Users collection of the Appery.io database (data storage: Appery.io database or user’s database).
  2. Authenticating with LDAP (data storage: Appery.io database or user’s database).
  3. Authenticating with Social network provider.

The two first options require creating a security provider: go to Resources > Security and click Add new security provider. Enter the Provider name and select the Provider type.

Using Appery.io database security for user authentication (cloud only)

Both cases described below (with data storage: Appery.io database or user’s database) require enabling Appery.io Database Security.

To enable user authentication with Appery.io Database Security, open: Resources > Security > Add new security provider, pass the Provider name, select this option from the drop-down and then select the Appery.io database you’d like to access with:
ApperySecurity

After testing for validity and saving, switch to the project under API EXPRESS, open the Settings tab and select this security provider for managing user access:

Unchecking the Allow only authenticated users to call REST box disables the section.

Data storage: Appery.io database

Now, to get access to the project, a user needs to enter his login and password (defined in the Users collection of the predefined Appery.io database) to access the data stored in Appery.io database.

Here is the authorization flow:

  1. A user invokes the login method of API Express and passes his/her username and password.
  2. API Express invokes the login method of Appery.io backend and passes the user’s username/password.
  3. If the Appery.io backend doesn’t return the session token, API Express returns information about the invalid credentials and the user gets the 403 error.
  4. If the Appery.io backend returns the session token, API Express generates the API Express session token, then saves both: the API Express session token and the backend session token, and returns the API Express session token to the user.
  5. The user invokes rest service of API Express (for example, find operation) and provides the session token.
  6. If API Express doesn’t find the session token in the session token storage, API Express returns information about the invalid session token and the user gets the 403 error.
  7. If API Express finds the session token in the session token storage, API Express invokes backend service with the backend session token and returns 200 response to the user.

Data storage: User’s database

The flow below describes the process of authorization with the user’s database (not Appery.io!) with user’s login and password (defined in the Users collection of the predefined Appery.io database) to obtain the token:

  1. A user invokes the login method of API Express and passes his/her username and password.
  2. API Express invokes the login method of Appery.io backend and passes the user’s username/password.
  3. If the Appery.io backend doesn’t return the session token, API Express returns information about the invalid credentials and the user gets the 403 error.
  4. If the Appery.io backend returns the session token, API Express generates the API Express session token, then saves both: the API Express session token and the backend session token, and returns the API Express session token to the user.
  5. Having obtained the API Express session token, the user invokes rest service of API Express (for example, find operation) and provides the session token.
  6. If API Express doesn’t find the session token in the session token storage, API Express returns information about the invalid session token and the user gets the 403 error.
  7. If API Express finds the session token in the session token storage, API Express invokes an sql query in the database and returns the 200 response to the user.

Read here how to make your database available for API Express.

Using LDAP for user authentication

Another option in securing Appery.io projects is using Lightweight Directory Access Protocol (LDAP) for user authentication.

Configuring a LDAP server as the backend database allows remote web authentication for retrieving user credentials and authenticating the user.

To configure it, go: Resources > Security > Add new security provider and, for Provider type, select LDAP.

The window with Security provider configurations opens. Fill in the required fields:

To ensure you enter valid data, click Test, then click Save.

Open the project under the API Express tab, and, under the Settings tab, select the LDAP security provider for managing user access.

Now, use your authorization credentials defined for LDAP.

Your Appery.io database credentials don’t apply in this case.

More information on LDAP can be found here.

Both cases described below (with data storage: Appery.io database or user’s database) demonstrate using LDAP as a security provider.

Data storage: Appery.io database

To access the data stored in Appery.io database and using LDAP as a security provider, follow the next steps:

  1. A user invokes the login method of API Express and passes his/her username and password.
  2. If API Express verification of the user username/password in LDAP fails, API Express returns information about the invalid credentials and the user gets the 403 error.
  3. If API Express verification is successful, API Express generates its session token, creates a user in Users collection with the same username as in LDAP (if it doesn’t exist yet), obtains the backend session token, saves both: the API Express session token and the backend session token, and then returns the API Express session token to the user.
  4. Having obtained the API Express session token, the user invokes rest service of API Express (for example, find operation) and provides the session token.
  5. If API Express doesn’t find the session token in the session token storage, API Express returns information about the invalid session token and the user gets the 403 error.
  6. If API Express finds the session token in the session token storage, it then finds the backend session token by the API Express session token and invokes backend service with the backend session token to return the 200 response to the user.

To enable creating a user in Users collection of the Appery.io database with the credentials identical to those of an LDAP user (Step 3), check the Save users for appery.io databases checkbox in the Security provider section under the Security tab:
SaveUsers

Here you can find the detailed tutorial describing authorization with your Appery.io database with LDAP as a security provider in API Express.

Data storage: User’s database

To access the data stored in user’s database and using LDAP as a security provider, follow the next steps:

  1. A user invokes the login method of API Express and passes his/her username and password.
  2. If API Express verification of the user username/password in LDAP fails, API Express returns information about the invalid credentials and the user gets the 403 error.
  3. If API Express verification is successful, API Express generates its session token, saves it in the session token storage, and then returns the API Express session token to the user.
  4. Having obtained the API Express session token, the user invokes rest service of API Express (for example, FIND operation) and provides the session token.
  5. If API Express doesn’t find the session token in the session token storage, API Express returns information about the invalid session token and the user gets the 403 error.
  6. If API Express finds the session token in the session token storage, it then finds the backend session token by the API Express session token and invokes backend service with the backend session token: an sql query in the database and returns the 200 response to the user.

Read here how to make your database available for API Express.

Authentication with social network provider (cloud only)

The process of authenticating with Social network provider for getting access to the data stored in the Appery.io database is like the follows:

  1. A user invokes the js login method of a social network (for example, loginFB for Facebook) and gets the backend session token.
  2. The user invokes the set SessionToken method of client SDK of API Express (it is requered only for work via client sdk).
  3. The user invokes rest service of API Express (for example, find operation) and provides the session token. Next two scenarios are possible:
  4. If API Express doesn’t find the session token in the session token storage, API Express starts searching for the session token in backend.
  5. If token isn’t found, API Express returns information about the invalid session token and the user gets the 403 error.
  6. If token is found, API Express saves it in the session token storage and invokes backend service with the backend session token to return the 200 response to the user.

More on Social login can be found here.

User authentication flow charts

The following flow charts illustrate all the API Express authentication cases.

Authentication can be done via Appery.io database (users are stored in _Users collection), LDAP or via social network.

Either Appery.io database or external database can be used as data storage.

Appery.io DB; Appery.io _Users

External DB; LDAP

Appery.io DB; LDAP

External DB; Appery.io _Users

Appery.io DB; social network

Offline mode

API Express supports offline mode that is made with help of ClientSDK. Here is how it works:

  • Initially, your app will be in online mode (state = online) no matter whether the internet on the device was enabled or not.
  • When the client goes offline (state = offline), all change-requests (POST, PUT, DELETE) to the server are going to be queued and stored to the Cache.
  • When the client goes online (state = synchronizing), the queue of deferred change-requests will be handled, and one after one, all the requests will be executed.
  • In case of a synchronization conflict (state = sync-failed), the error will be stored.

When a device is connected to the internet, CliendSDK synchronises to the server and sends all offline changes made by the user. The mobile app automatically detects a connection state and switches the CliendSDK to an online/offline mode when the connection state has changes. In AppClientSettings service there is an option called handleNetworkState that is activated by default. You can disable this if need be.

There are few functions in ClientSDK library that help to handle switching between online and offline modes, and also trigger the synchronization or reset data that failed to sync. Initially, ClientSDK is not included in your Appery.io app. It will be added to the app as AppClientInit.js (it will be listed under JavaScript folder), during services generation via API Express Generator extension.

goOffline

ClientSDK can change the mode to offline from an online state only. During any offline work all of the calls to the server will be deferred (persisted in localStorage/indexedDB in a queue).

For AngularJS projects, the following works:

For jQM projects:

goOnline

ClientSDK can switch the app mode to online only from offline state. During the process of going online, deferred server calls stored in the cache are to be performed during this synchronisation process –  state = synchronising.

Every cached operation will be executed one-by-one. The Synchronisation process will stop in case of an error (state = sync-failed).

For AngularJS projects:

For jQM projects:

retrySync

retrySync function can be executed to retry the synchronisation process and will work only when state = sync-failed.

For AngularJS projects:

For jQM projects:

resetFailedSync

resetFailedSync will erase all of the operations that were not performed successfully. The operations that were executed successfully will not be affected; it will only work when state = sync-failed.

After this operation execution, switching the app mode to online will be performed.

For AngularJS projects:

For jQM projects:

getState

Use getState method to determine the current app state.

For AngularJS projects:

Here is how the state can be shown in the console:

jQM projects:

revertLocalChanges

Use the revertLocalChanges method to revert all local changes made in offline mode without clearing the cached data. It can also be useful in case of a failed synchronisation or conflicted objects.

For AngularJS projects:

jQM projects:

getDeferredActions

By using the getDeferredAction you will return the iterator, which you can use further to iterate through the array items. History in this case is the type of array. This array contains deferred actions that will be executed only if app goes online, so that is why they are deferred.

For AngularJS projects:

jQM projects:

A retrieved object (called historyIterator in current example) has the following methods:

  • next() – returns JSON object of the stored action with following structure:
    • done – end of history items indicator, if true then there are no more history items.
    • value – actual history item value has the following structure:
  • remove() – removes current action from the history.

saveDeferredActions

If you modified the history of saved deferred actions, you should save the changes by using the saveDeferredActions method.

For AngularJS projects:

jQM projects:

Using API Express in your app

One of the great features of the API Express is that once your database is exposed via REST services, you can easily integrate it with your Appery.io mobile app.

Using the API Express Generator extension

By using the API Express Generator extension, you can generate multiple REST services based on models created via API Express. Then you can use them inside the app as usual to perform CRUD operations.

Read more about the API Express Generator here.

Using ClientSDK test page

ClientSDK.js is the library that is responsible for all calls between your Appery.io app and your database used in API Express. This library is used inside the Appery.io core (API Express Generator uses it). There is a ClientSDK webpage page that you can use to test created database connections, user authentication, perform CRUD operations, and more, all easily and in one place:
SDK

It’s just a visual representation of the ClientSDK API, so every button simply triggers certain ClientSDK functions.

Here’s a few tips for using it:

  • Type appery.io for Server.
  • Copy the APIKey from API Express > Settings.
  • Click Initialize to try to connect. If it was successful, you’s see the models to choose from, and if something went wrong, you’ll see the error.
    header
  • Click Find under Find Options to get the first 100 records from the table.
  • You can type search filters in the light-yellow box (marked as WHERE), and clicking Find will return the results based on this filter:
    find
  • The Get Count button will simply return the amount of records.
  • If you checked Allow only authenticated users to call REST under the API Express > Settings you should authenticate to perform actions. Type the credentials and click Login. If something went wrong, you will see the error, but you will see nothing in the case of success.
  • You can retrieve any record by its id. To do this, type the value of the id parameter in the ENTITY ID box. Click Get by id to test:
    get_by_id
  • You can delete the entity by id the same way by clicking Delete.
  • To create a new record, provide JSON inside the light-green box and click Create (don’t specify id if auto increment is turned on in your database):
    create
  • Specify record id in the ENTITY ID field and parameters to update in the ENTITY CONTENT fields. Click Update to update that record.
  • By using the SDK State Methods block, you can simulate the offline mode. All changes that were made in offline mode will be shown in the bottom-left block.
  • If you didn’t specify to use mandatory authentication, synchronization will be performed once Go online is clicked.
  • Otherwise, synchronization should be started manually after going online by clicking Retry sync.
  • Reset failed sync state will reset the synchronization failed state – in other words, all operations made offline will never be synchronized.

Best practices

This section shows best practices for using the visual builder to create advanced services.

Generating Generic Services in Visual Builder

This example will show you how to generate a generic service from custom REST service using API Express Generator extension.

For example, you have already set up connection to your PostgreSQL database where you store information about books in a collection named ms_book.

Follow the steps below to create an app that displays a book author depending on the entered path key.

API Express

  1. Select Start component and set URL template = custom/{key}.
  2. Add SQL component and set database connection = PostgreSQL
  3. Enter the following query:
  4. Click Parse SQL parameters. Click Generate.
  5. Set PARAMS.PATH.key = 0000111. Click Run SQL, click Import response.
  6. Save custom REST service. The custom REST service that accepts one path parameter is created. It has the following JSON response:
  7. Make sure SQL component properties look like here:
    SQL

App Builder

  1. Create an Appery.io app that will use this custom REST service.
  2. Click CREATE NEW > Extensions > API Express Generator.
  3. Choose Appery.io domain, click Next.
  4. Select required API Express project, then select REST "GET" custom/{key} service.
  5. Enter service name CustomService, click OK.
  6. Refresh the app builder to see the generic service with name CustomService is generated.
  7. Let’s invoke it and display the data from the REST service response.

Design tab

  1. Open Screen1.
  2. Add Input with property ng-model = key.
  3. Add Button with property ng-click = onClick();.
  4. Add Label with property Text = {{author}}.

Scope tab

  1. Open Scope tab.
  2. Add Scope variables key and author.
  3. Add Scope function onClick().
  4. Click Invoke service snippet and select your custom service name in autocomplete list.
  5. Request mapping: map key to key.
  6. Response mapping: map author to author.
  7. Add this code in the end of Success event handler:
  8. The final code is the following: