Connecting to APIs

Connecting to API (deprecated).

🚧

Information about this section

The approach described in this section is no longer recommended. Instead use the new API integration approach.

More notes:

  • Custom and enterprise plans can request to connect to external APIs directly from the client.
  • If your Appery.io account was created before July 16, 2016 you still have this option available, however we recommend to use the new approach. Accounts created after this date should use the new approach only.

Introduction

You can use REST services to integrate backend cloud services that support RESTful APIs. Like any other service, REST services usually have inputs and outputs, and must be set up within Appery.io.

Creating a service consists of:

  1. Entering the service URL.
  2. Defining the request parameters (the input).
  3. Defining the response parameters (the output).

Create New Service

To create a new service, from Project view select Create New > Service. Enter a service name and click Create Service. The service will open up in a new tab that has the following views:

  • Settings – define the main options for the service.
  • Request – add request headers (Headers tab), input parameters (Query String tab), and set default values, if needed.
  • Response – define output headers (Headers tab) and parameters (Body tab).
  • Test – test the service, and create a service response based on the test results.
  • Echo – get data from the service without invoking it.

Settings view allows you to set the:

  • Name – a service name.
  • URL – service URL, which allows access to public (without authorization) or private (requires authorization) data. Read about using dynamic URLs.
  • Method – type of request:
    • Get – requests data from a specified resource.
    • Post – submits data to be processed to a specified resource.
    • Put – uploads the specified data (a complete replacement of data).
    • Patch – updates data (applies partial modifications to a resource).
    • Delete – deletes data from the specified resource.
  • Data Type – format of the data returned by the service:
    • JSON – JavaScript Object Notation: text-based open standard, designed for human-readable data exchange between the browser and server.
    • JSONP- JSON with padding: provides a method to request data from a server in a different domain.
    • XML – Extensible Markup Language: a set of rules for encoding documents in a format that is both human-readable and machine-readable.
  • Settings – the settings service can be selected from the drop-down list.
  • Security Context – a generic security service running JavaScript code before or after the REST service execution.
  • Content Type – when you use the POST, PATCH, and PUT methods, you can specify how the data should be encoded when submitting it to the server. A list of name/value pairs depends on the value you set to this parameter:
    • JSON: application/json application/javascript text/javascript
    • XML: application/xml text/xml application/xhtml+xml application/atom+xml
    • x-www-form-urlencoded: application/x-www-form-urlencoded
    • data: application/octet-stream
  • Appery.io Proxy – if your service doesn’t support cross-domain calls, you can check this box to provide a proxy service that works for testing.

Add the Service to a Page

Once a service has been defined, it can be added and mapped to one or more pages. To add a service to a page:

  • Go to the page where you need to use this service.
  • Switch to Data view by clicking the Data tab.
  • Add a datasource, select Service, and then the service you’ve created.
  • Click the Add button. A service instance is added to the page.

By default, the service instance is named restserviceX. You can change it to a more meaningful name by setting its name property.

Request Parameters

Request view allows you to define the request parameters and headers required by the service to be invoked. Every service can define a different number of request parameters. Some parameters are required; others may be optional. Some services don’t require any request parameters at all.

To create, edit, or delete request parameters, open Request view and switch to Query String tab.

Query Parameters

To create a new parameter, enter its name and click Add.

If a service request parameter value doesn’t change, you can set its default value. The following example shows two parameters set to default values.

When you use the service on a page you can use the default values, or you can map the page component properties to the parameters instead.

You can add a set of request parameters by importing query string. To do this click Import and enter a query string in the newly-appeared window.

Click Import to add a request parameter based on the provided data. The imported query string should be composed as a series of field-value pairs as in the following:

param1=value&param2=value

Request Headers

Some services require one or more request parameters to be sent as Header. Header parameters should be added on the Request > Headers tab.

You can add a set of request headers at once by using the Import feature. Headers should be specified as field-value pairs. Use the line break as a separator between pairs as followed:

header1: value
header2: value

Request Body

When you use POST, PUT or PATCH methods the new Body tab appears in Request view. Its type is based on the Content Type chosen in the REST Service settings. If Content Type is set to Data, the Request Body contains a single parameter which you can’t modify.

When adding the service to a page, you can map binary data (e.g. files) to this parameter.

Default Request Parameters Value

You are not required to map every service input parameter to an element on the page. It is possible to set a default value for an input parameter by simply entering any value.

You can also use JavaScript to provide a default value. Click JS and provide a default value or an expression that will calculate a value.

return "12345";

Return current day of month:

var currentDate = new Date();
return currentDate.getDate();

Return value from the Input component entered by user:

return Apperyio('input_field').val();

If you set default values during a service creation, then those values are automatically copied to the service instance mapping.

Response Parameters

Response view allows you to define the response parameters that the service returns. Response view consists of two tabs – Headers and Body. The Headers tab contain headers that should be returned in the service response. The Body tab contains all other response data. Services may return data in JSON, JSONP or XML format. You can set the return data form in the Settings view.

To define the response parameters manually, open up Response view and switch to the Body tab. First, you need to choose the type for the response root element. It can be type of Object or an Array. You can’t remove the response root element. Choose Array if your service should return an array (for example, list of customers) or choose Object, if your service should return single set of data (for example, information about certain customer).

To add a response parameter, enter the output parameter’s name, and click Add. The parameter appears in the list.

In the case of using an Array type for a response root element, there are two parameters that can’t be removed: $ – the array itself and $[i] – each value of array (see Mapping for more about this).

Response parameters and array elements ($[i]) can be any JSON types. You can create more complex response structures to fit your needs.

In the example above, there is the root element ($) type of array, which means that the defined structure can be repeated multiple times (for every customer). $[i] – is a reference to every array element, and it can be used further for mapping purposes. Next, there are several fields with different data types that correspond to field types stored in the database.

Import Response Headers

Response headers can be imported the same way as request headers. Open Response > Headers and click Import. Provide headers that are composed as field-value pairs, and divide them with a line break like the following:

header1: value
header2: value

Import Response Body

You can add a set of response parameters by importing JSON (for JSON or JSONP Data Type specified in the service Settings) or XML (for XML Data Type). Go to Response > Body and click Import. Use the following syntax for JSON or JSONP Data Types:

{"param1":"paramValue",
"param2":"paramValue2"}

Use the following syntax for XML Data Type:

<root>
<username></username>
<useraddress></useraddress>
</root>

Automatically Define Response

You can define response parameters automatically when testing the service (in Test view). Once you’ve defined the service properties, and defined one or more request parameters, you can quickly test the service to make sure it works and returns a valid response. Defining the response manually can become a time consuming and error-prone process; very often the service returns a lot of data. It’s possible to create the response automatically after testing the service.

To test the service and create a response, follow these steps:

  1. Switch to Test view.
  2. Enter values for the request parameters. If you set the default values, you can see them.
  3. Click Test. The service is invoked and the result will appear in the Response area.
  4. Click Import as Response. The service response parameters will be created based on the returned data.
  5. Switch to Response > Body view to see the generated response.

Incorrect Format Error

You can get the following incorrect format error message when trying to create the response: Incorrect format. Please verify sample response data and try again. The first thing you should do is check whether the format is valid. A good way to check is by using a JSON Validator http://jsonlint.com or XML validation http://www.xmlvalidation.com/. If the JSON is valid, copy the data from http://jsonlint.com window, paste it into the service editor (Response > Create from Sample Response), and try again.

Service Testing

Once you’ve defined the service properties and one or more request parameters, you can quickly test the service to make sure it works and returns a valid response.

To test the service:

  1. Switch to Test view.
  2. Enter some values for request parameters. If you set default values, you can see them.
  3. Click Test. The service is invoked and the result appears in the Response area.

Using Echo

In the Echo view you can enable an Echo service, which allows you to get data from a service without invoking it. It’s like a mock service.

It works by you giving a sample response from a service to Appery.io. When it invokes the service, Appery.io uses this (static) sample, instead of actually invoking the service.

To enable the Echo service:

  1. Switch to Echo view, and check the Enable Echo box.
  2. Paste a sample service response.

Controlling Echo In Runtime

You can also control Echo via JavaScript in run time. You can set it to any string, which contains data in a corresponding format (JSON, XML) in run time:

service_name.__requestOptions.echo = '{"login":"[email protected]", "password":"abc"}';

To turn Echo off:

service_name.__requestOptions.echo = '';

Parameters In URL (Dynamic URL)

If you need to configure the URL with dynamic parts, define the service URL with parameters using {}. For example:
http://mywebsite.com/name/edit/{id}
or:
http://mywebsite.com/name/{id}/edit

Where the id would be set when the service is invoked. In this case, id would need to be defined as a request parameter.

Also, id can be specified in the Settings file.

Any part of the URL can be expanded this way, even the entire URL.

📘

Note

Header parameters are not used for service request URL.

Alternatively, the URL with dynamic parameter can be passed under the Settings tab of the particular REST service.

The parameter id, when added under the REST service Query String tab.
Or passed in the first level under Body on theRequest tab.
Substituted parameters will not be added to the URL, but will replace the corresponding URL parameter instead.

📘

Note

The parameters substituted aren’t included into the request.

Escaping Special Characters In URL

It is good practice to avoid using the special characters when formulating a URL string. In case you need to pass the characters below, the corresponding escape characters must be used instead, so that the browser parses your code it will not misinterpret the link:

Character
Space%20#%23
$%24%%25
&%26@%40
`%60/%2F
:%3A;%3B
<%3C=%3D
>%3E?%3F
[%5B\%5C
]%5D^%5E
{%7B|%7C
}%7D~%7E
%22%27
+%2B,%2C

Invocation Order

By default, services are invoked in an asynchronous order. Let’s say there is Service A and Service B, and both are invoked in order on a button click:

  1. Service A.
  2. Service B.
    There is no guarantee that Service A will finish before Service B is invoked. When Service A is invoked, the execution then moves to Service B. If you need to ensure that Service B is only invoked after Service A is finished, then use a Service A Success event to invoke Service B.

Invoking from JavaScript

To invoke any service directly from JavaScript, use:

serviceInstanceName.execute({});

serviceInstanceName – is the name of the service instance from DATA view.

For instance, you have a datasource get_instruments.
Use following JavaScript code to invoke the service:

get_instruments.execute({});

Passing Parameters

You can also pass a request parameters and header request parameters when invoking via JavaScript by using following syntax:

serviceInstanceName.execute({
    data:{},
    headers:{}
});

Here is how you can pass a where parameter to the get_instruments service :

get_instruments.execute({
    data:{
   'where':{'name':'Drum Kit'}
   },
    headers:{}
});

Basic Authentication

  • Add the following as an external resource in Project > App profile > External resources:
    http://crypto-js.googlecode.com/files/2.5.3-crypto-min.js
  • You may also add this as a JavaScript file by simply copying the entire content of the file.
  • Create the following JavaScript file (note that username:password needs to be a string):
function getAuth() {
   var bytes = Crypto.charenc.Binary.stringToBytes('username:password');
   var base64 = Crypto.util.bytesToBase64(bytes);
   return "Basic " + base64;
}
  • Create the service.
  • Add an Authorization request header.
  • Add the service to the page.
  • Open service's Before send mapping
  • For the Authorization parameter, click JS and enter the following JavaScript:
return getAuth();

You can now test the service on the page.

Testing Service

  • Run the service once as described below.
  • Use Chrome Developer Tools (or Firebug), open the Network tab and view the request headers sent. You’ll see something like:
Authorization: Basic a2lkURA2NzpkNmYxOTQ2ZUWXMzI0YzhkYTabNjNjMGNkMTMzNzUxNA==
  • You can now take the Authorization value (Basic a2lkURA2NzpkNmYxOTQ2ZUWXMzI0YzhkYTabNjNjMGNkMTMzNzUxNA==) and use it as a request parameter for the service.

Secure Proxy

Introduction

Appery.io Proxy – is a service that can be used for testing in desktop browsers to avoid cross-domain security problems. When using the proxy, the request is first sent to the proxy server, and then from the server, the request is made to the service. Because the request is sent from the server and not from the page, cross-domain security is not triggered.

Appery.io provides two kinds of proxies – default and secure proxy.

The Secure Proxy feature additionally allows you to keep your secret keys, credentials, or other data safe from being accessed by app users.

A Secure Proxy works in this way:

  • You store your secret data in a database under key names.
  • Then you create a secure proxy for replacing the key names with secret data.
  • In the app, you use key names and define the proxy that should be used.
  • The app invokes a REST Service that contains key names, and on the server-side key names are replaced with its appropriate values.

Using the app, you can find the key and proxy names, but you have no access to the secured data.

Creating an Appery.io Default Proxy

  1. Switch to the Secure Proxy tab.
  2. To create a new proxy, click Create new proxy and enter the proxy name.
  3. The created proxy opens with default settings.
  4. The Proxy ID and Proxy name are unique values. Proxy name is used to define the proxy channel in the app.
  5. Now this proxy can be chosen from the Appery.io builder.

📘

Note

If you set Response Data Type – JSONP, the Appery.io proxy cannot be used.

After that, using the proxy will be automatically turned on for this REST service.

Create Proxy From The Appery.io Builder

Proxies can also be created from inside the Appery.io builder:
1.Click New Channel on the Settings tab of any REST Service.
2. Enter name for new proxy and click Create.
Once the new proxy is created, using the proxy for this service will be automatically enabled with it:

📘

Note

Only the default proxy can be created from the builder.

Using The Secure Proxy

As mentioned above, by using Secure Proxy you can secure sensitive data by keeping it only in the database. In this case only the keys (not their values) will be used inside the app.

Storing Private Data In The Database

  1. Open the Appery.io Databases tab.
  2. Create a new database or use an existing one.
  3. Create a new collection, and enter any name (for example, secretKeys).
  4. Add two columns: keyName and secretValue. Use any names, but note that these names should be easily identifiable.
  5. Enter your data. Key names are used in the app. You can use letters, numbers and spaces in key names.

You can create a unique collection for each app, or you can create one database collection that stores private data for all your apps.

Configuring The Secure Proxy

  1. To use Secure Proxy, switch to the Secure Proxy > Proxy tab, open created proxy and check the Use proxy + store sensitive (private) data in database.
  2. In the opened drop-down menus, select the needed parameters.
  3. Click Save.

One database can be used in a different proxy, just as the one proxy can be used for different apps. You can also use several proxies in one app.

Using A Secure Proxy In The App

  1. Open your Appery.io app and open the REST Service that should use Secure Proxy features.
  2. On the Settings tab of that service select created Secure Proxy from the list.
  3. In Request view, set the key name from the database in braces {KeyName} as the default value for the corresponding input parameters.
  4. Test the app in the browser and invoke the needed REST Service. No actual data will be sent from the app.
  5. When testing the service on the Test tab of the REST Service, enter the actual data instead of the key names otherwise the test will fail.

Restricting URLs Access

Using Secure Proxy also allows creating a list of allowed URLs. This way you can restrict all URLs except the ones you need. Be sure that your requests will not be redirected for hacking purposes.

📘

Note

You can’t use the Allowed URLs feature without specifying Database, Collection, Key column and Value column.

  1. Go to the Secure Proxy tab and open your proxy.
  2. Find the Allowed URLs title and add URLs by typing them into text field to the right and clicking Add. Here is how you can allow access only to the appery.io and api.worldweatheronline.com.

All other URLs will not be accessible through the REST Service that uses this proxy and the following error will be returned:

{"code":"PTCT036","description":"Specified URL is not allowed"}

You can use the asterisk symbol as mask to replace any number of characters in the URL. For example:
https://*.worldweatheronline.com

The asterisk symbol is also automatically added to the end of every URL.

📘

Note

Applying changes for allowed URLs takes 1 minute.

Using Old Proxy Implementation.

Proxy implementation was updated and all of your proxies were automatically switched to the new version. The new implementation is faster, and it’s strongly recommended that you use it. The old proxy implementation will be deprecated after a while.

However, if you’re facing any problems with the new proxy implementation, you can switch back to the old version by checking Use old proxy implementation (slower) on the proxy page.
The under-the-hood library in the old proxy implementation supports providing username:password directly in the URL, e.g.:
http://user:[email protected]

In case you experience problems with the new proxy, please contact Appery.io support.

The section Share with support is placed at the bottom of the page. When a user enables sharing (turns the toggle on), the specified resource appears in the admin section. This feature can be used by the support team for viewing and accessing all resources (apps, databases, server scripts, etc) shared.

HTTP Basic Authentication

Some REST API services use HTTP basic authentication to authenticate users. One such service is the Twilio API. You would provide the username and password in the URL. For example:
http://username:[email protected]/

This approach is being phased out by most modern browsers. You can find more information on it for each browser: Chrome, Firefox, IE.

The under-the-hood library that we use for the new Appery.io Proxy also doesn’t support this authentication method (it’s not a bug, the creators of the library decided not to support this). The solution to this problme is to switch to Basic header-based authentication,

Basic Header-Based Authentication

Switching to Basic header-based authentication is very simple. You need to complete the following steps (from MDN):

  1. Username and password are combined into a string username:password
  2. The resulting string literal is then encoded using Base64
  3. The authorization method and a space, i.e. Basic is then put before the encoded string
  4. A header is added to a service in the following form: Authorization Basic
    For example, if the username is: my_user and the password is: my big secret, then the header and the encoded string would look like this:
Authorization: Basic bXlfdXNlcjpteSBiaWcgc2VjcmV0

To encode a string into Base64 string can be easily done with the browser’s built-in function window.btoa(string). For example, you can run this from browser’s console:

window.btoa("my_user:my big secret");

Which will result in:
bXlfdXNlcjpteSBiaWcgc2VjcmV0

When you test a service in Appery.io, you can set the entire string as Authentication header default value:
Basic bXlfdXNlcjpteSBiaWcgc2VjcmV0

Alternatively, you can run a JavaScript function during mapping:

return "Basic " + window.btoa(username+":"+password);

This approach will allow you to use the new proxy (or the old proxy).

📘

Note

To make secure proxy work, you need to write into the database already encoded content of Authorization header and in the service value field specify something like: Basic {auth_data}.

Permissions Tab

On the Permissions tab, you can specify the access permissions (View, Edit or Delete) you give the users of your team.

The user the proxy was shared with will see it under the Secure Proxy tab.
The user the proxy was shared with can open it to view or edit, delete or clone it (if granted such rights).

📘

Note

Editing the proxy will cause the original proxy to change. To edit the shared secure proxy without affecting its original, use Clone to make a unique copy of it.