Console
Console API.
Used to print data for information or debugging purposes.
Method summary
Console has the following methods:
log("format", data1, data2, ...)
Writes specified data to trace.
dir(object)
Displays object data into the trace.
assert(expression,message)
Logs message only when expression is false.
time(label)
Marks timer to log execution time.
timeEnd(label)
Finishes timer, records output.
trace(label)
Prints stack trace.
log
console.log(format, data1, data2...)
Writes specified data to the trace. If the first argument is a formatted string, the output will be formatted according to it. Data is any of the following types: string, number, boolean, array, and object.
format
Optional. If the first argument is a formatted string, the output will be formatted according to it.
dataN
Any of the types: string, number, boolean, array, object.
time
console.time()
Starts a timer that allows you to track how log an operation takes. Collaborates with timeEnd(), which ends the timer.
label
A unique string label for this timer. Use the same label to in timeEnd to end timer execution.
dir
console.dir(object)
assert
console.assert(expression, message)
Logs message only when the expression is false.
expression
Express to evaluate.
message
Message to print if express evaluates to false.
timeEnd
console.timeEnd(label)
Used to finish the timer started by time(label) method. This method accepts the name of the timer started and prints the output.
label
The name of the timer to end.
trace
console.trace(object)
Prints the stack trace from the point where this method was invoked. It also prints the line code in the script where the method was invoked.
object
Optional. If an object is passed to the method its content will be printed to the console.
Collection
Server Code API to work with the database.
Collection API integration with the Appery.io database. With this API you can access the database, search the database, create, update, and delete objects.
Using Server Code to Access the Database
We recommend to access the database from the Server Code instead of accessing the database directly from the app. This approach has the following benefits:
- Sort the database results.
- Filter the database results.
- Query the database two or more times.
- Run any custom logic before, or after querying the database.
getCollectionList(dbApiKey)
Returns a list of a collection info of a specific database.
createObject(dbApiKey, collectionName, objectJSON[, token])
Creates an object in the specified collection.
retrieveObject(dbApiKey, collectionName, objectId, include[, proj][, token])
Retrieves an object from the specified collection.
updateObject(dbApiKey, collectionName, objectId, objectJSON[, token])
Updates object into the specified collection.
multiUpdateObject(dbApiKey, collectionName, queryString, updateJSON, operationsJSON[, token])
Updates multiple objects by specified values.
deleteObject(dbApiKey, collectionName, objectId[, token])
Deletes object from the specified collection.
multiDeleteObject(dbApiKey, collectionName, queryString[, token])
Deletes multiple objects from the specified collection that matches specified criteria.
query(dbApiKey, collectionName[, params][, token])
Queries a list of objects from a specified collection.
distinct(dbApiKey, collectionName, columnName[, queryString][, token])
Queries a list of distinct values from a specified collection’s column.
deleteObject
Collection.deleteObject(dbApiKey, collectionName, objectId[, token])
Deletes an object from a specified collection.
Parameters
The function has the following parameters:
dbApiKey
Database API key.
Yes.
token
String with user token or database Master key.
No.
collectionName
String with database collection name.
Yes.
objectId
ID of object that should be deleted.
Yes
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
Collection.deleteObject(dbApiKey, "Student", "57a52a1be4b0288ba31f1833");
The method returns empty response body with code 200.
multiUpdateObject
Collection.multiUpdateObject(dbApiKey, collectionName, queryString, updateJSON, operationsJSON[, token])
Updates multiple objects selected by a query with new values. The function returns a 200 code with empty response body.
Parameters
The method has the following parameters:
dbApiKey
Database API key.
Yes.
token
String with user token or database Master key.
No.
collectionName
String with database collection name.
Yes.
queryString
Query to select which objects will be updated. The JSON query object that was built in accordance with the documentation of MongoDB query.
Yes.
updateJSON
JSON object with fields of object that should be updated.
No.
operationsJSON
JSON update object with native MongoDB operations and fields of object that should be updated. The object was built in accordance with the documentation of MongoDB set operations.
If <operationsJSON> object specified than update <updateJSON> param fully ignored. Their functionality cannot be used simultaneously. The following operations are supported:
- $set
- $unset
- $inc (Number type only)
- $mul (Number type only)
- $min (Number and Date type only)
- $max (Number and Date type only).
Native operations works on the following data types: number, string, boolean, date.
No.
Examples
The following examples finds all students who are transfer students and the update sets their major to undecided. This examples uses updateJSON parameter.
var dbApiKey = "57928860e4b00ef864f3dc24"
var result = Collection.multiUpdateObject(dbApiKey, "Student", '{isTransferStudent: true}', {"major": {'name':'undecided'}
});
This example performs an update suing the native MongoDB operaitons (with operationsJSON parameter). This code will change any students who are transfer student to non-transfer students.
var dbApiKey = "57928860e4b00ef864f3dc24"
var result = Collection.multiUpdateObject(dbApiKey, "Student", '{isTransferStudent: true}', null, {
"$set": {"isTransferStudent":false}
});
Not that native operations works on the following data types: number, string, boolean, date.
getCollectionList
Collection.getCollectionList(dbApiKey)
distinct
Collection.distinct(dbId, collectionName, columnName[, queryString][, token])
Queries a list of distinct values from a specified collections column.
Parameters
This function has the following parameters:
dbApiKey
String with database API key.
Yes.
token
String with user token or database Master key.
No.
collectionName
String with database collection name.
Yes.
columnName
String with database column name on which distinct operation will be invoked.
Yes.
queryString
Query to select particular objects on which to invoke the distinct operation. JSON query object that was built in accordance with the Mongo querying documentation.
No.
Examples
This example will retrieve all distinct values from major column. Distinct will return only data from the specified column. In other words, other collection data (columns) are not returned. The Result tab shows information assuming the collection only has English and Chemistry as majors.
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
result = Collection.distinct(dbApiKey, "Student", "major");
[
{
"name": "English"
},
{
"name": "Chemistry"
}
]
This example will retrieve distinct values from column named Size but only for values greater than 10:
multiDeleteObject
Collection.multiDeleteObject(dbApiKey, collectionName, queryString[, token])
Deletes multiple objects from a specified collection that matches specified criteria (queryString). The method will return a 200 status code on successful delete and empty body.
Parameters
The method has the following parameters:
dbApiKy
String with database id.
Yes.
token
String with user token or database Master key.
No.
collectionName
String with name of collection.
Yes.
queryString
JSON query object that was built in accordance with the MongoDB querying documentation.
Yes.
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var result = Collection.multiDeleteObject(dbApiKey, "Student", {isTransferStudent: false});
updateObject
Collection.updateObject(dbApiKey, collectionName, objectId, objectJSON[, token])
dbApiKey
Database API key.
Yes.
token
String with user token or database master key.
No.
collectionName
String with name of collection.
Yes.
objectID
Unique identifier of object that should be updated.
Yes.
objectJSON
JSON object which holds columns and new data. Only field which are sent in this object will be updated. Columns not present will not be updated.
Yes.
_updatedAt
Time stamp when the object was modified.
{
"_updatedAt":{"$date":<update>}
}
Examples
This example shows how to update three columns in the Student collection. Columns for which data is not sent are not updated (values are unchanged).
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var result = Collection.updateObject(dbApiKey, "Student", "57a52796e4b03647ddae32a5", {
"isTransferStudent": true,
"major": {"name":"Biology"},
"courses": [300, 305]
});
{
"_updatedAt": {
"$date": "2016-08-06T00:15:41.350Z"
}
}
You can also provide a session token if security is enabled for this collection:
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var token = "...";
var result = Collection.updateObject(dbApiKey, "Student", "57a52796e4b03647ddae32a5", {
"isTransferStudent": true,
"major": {"name":"Biology"},
"courses": [300, 305]
}, token);
query (search)
Collection.query(dbId, collectionName[, params][, token])
Queries (searches) a list of objects from a specified collection.
Parameters
The method has the following parameters:
dbApiKey
String with database API key.
Yes.
collectionName
String with name of database collection.
Yes.
params
JSON object that contains request parameters:
- criteria – JSON – queries the object that was built in accordance with the mongo querying documentation.
- skip – integer – parameter indicating how many objects should be skipped before including objects into the response.
- limit – integer – parameter indicating how many objects should be included in response.
- count – boolean – parameter indicating whether to include or not include the number of selected objects in the response;
- sort – string – list of fields names split by commas that indicate order of objects in response.
- include – string – parameter indicating whether the referenced object should or shouldn’t be included.
- proj – JSON projection object that was built in accordance with the documentation of mongo quering.
Yes.
token
String with user token or database Master key.
No. Only required if the collection is secured.
[{
"_id":<object_id>,
<colName>:<value>,
"_createdAt":{"$date":<create_date>},
"_updatedAt":{"$date":<update>}
},
]
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var params = {};
params.criteria = {
"lastName": {
"$eq": "Lee"
}
};
var result = Collection.query(dbApiKey, "Student", params);
[
{
"major": {
"name": "English"
},
"isTransferStudent": true,
"courses": [
300,
305
],
"lastName": "Lee",
"firstName": "Anna",
"_id": "57a52796e4b03647ddae32a5",
"_updatedAt": {
"$date": "2016-08-08T19:11:36.301Z"
},
"toAddress": {
"collName": "Address",
"_id": "57a5199be4b03647ddae3297"
},
"_createdAt": {
"$date": "2016-08-05T23:56:06.051Z"
}
},
{
"isTransferStudent": true,
"_updatedAt": {
"$date": "2016-08-08T20:46:23.833Z"
},
"toAddress": {
"collName": "Address",
"_id": "57a52992e4b03647ddae32a8"
},
"lastName": "Lee",
"courses": [
100,
101
],
"firstName": "Sarah",
"_id": "57a8ed82e4b081a83615fc33",
"major": {
"name": "Chemistry"
},
"_createdAt": {
"$date": "2016-08-08T20:37:22.486Z"
}
}
]
The following examples is the same as the first one but now with a session token:
var user = DatabaseUser.login("c33010af-f263-4443-9897-c2ffaf522956", "admin", "123");
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var params = {};
params.criteria = {
"lastName": {
"$eq": "Lee"
}
};
var result = Collection.query(dbApiKey, "Student", params, user.sesssionToken);
[
{
"major": {
"name": "English"
},
"isTransferStudent": true,
"courses": [
300,
305
],
"lastName": "Lee",
"firstName": "Anna",
"_id": "57a52796e4b03647ddae32a5",
"_updatedAt": {
"$date": "2016-08-08T19:11:36.301Z"
},
"toAddress": {
"collName": "Address",
"_id": "57a5199be4b03647ddae3297"
},
"_createdAt": {
"$date": "2016-08-05T23:56:06.051Z"
}
},
{
"isTransferStudent": true,
"_updatedAt": {
"$date": "2016-08-08T20:46:23.833Z"
},
"toAddress": {
"collName": "Address",
"_id": "57a52992e4b03647ddae32a8"
},
"lastName": "Lee",
"courses": [
100,
101
],
"firstName": "Sarah",
"_id": "57a8ed82e4b081a83615fc33",
"major": {
"name": "Chemistry"
},
"_createdAt": {
"$date": "2016-08-08T20:37:22.486Z"
}
}
]
This example shows how to count the number of objects in a collection:
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var result = Collection.query(dbApiKey, "Student", {"count": 1});
[
{
"count": 20
}
]
This example shows how to search by the built-in _updatedAt column:
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var now = new Date ();
var params = {};
params.criteria = {
"_updatedAt": {
"$lt": {$date: now.toISOString()}
}
};
var result = Collection.query(dbApiKey, "Goods", params);
Apperyio.response.success(result, "application/json");
// Returns all objects updated before 'now'.
You can also use the built-in _createdAt column the same way.
The following examples hows how to search by a custom field of Date type. Note that the syntax is slightly different than when using the built-in date columns.
ISO Format
When using one of the built-in data types in a query (_createdAt, _updatedAt), the date value must be formatted in ISO format. When using a custom column with Date type, using ISO format is not required.
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var params = {};
params.criteria = {
"startTime": {
"$gt": "2016-12-31 00:00:00.000"
}
};
var result = Collection.query(dbApiKey, "Goods", params);
Apperyio.response.success(result, "application/json");
// Returns all items where startTime is greater than Dec 31, 2016
The following examples uses two date columns:
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var params = {};
params.criteria = {
"$and": [{
"startTime": {
"$gt": "2016-12-31 00:00:00.000"
}
}, {
"endTime": {
"$lt": "2017-02-01 00:00:00.000"
}
}]
};
var result = Collection.query(dbApiKey, "Goods", params);
Apperyio.response.success(result, "application/json");
// Returns all items where time is between December 31, 2016 and February 1, 2017
createObject
Collection.createObject(dbApiKey, collectionName, objectJSON[, token])
dbApiKey
Database API key.
Yes.
collectionName
Collection name in which to create a new object.
Yes.
objectJSON
JSON object with the content of the new object based on collection structure.
Yes.
token
Session token or database master key. Required if the collection has security enabled.
No.
Response
Response for a successfully created object (regardless of the data used to create the object).
_id
ID of the object created.
_createdAt
Date when the object was created.
{
_id: '5783eb10975afbb10a042f0c',
_createdAt: {
'$date': '2016-07-11T18:53:04.287Z'
}
}
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var result = Collection.createObject(dbApiKey, "Student", {
"firstName": "James",
"lastName": "Brown",
"isTransferStudent": true,
"courses":[100, 101],
"major": {"name":"Chemistry"},
"toAddress": {"collName": "Address", "_id": "57a52992e4b03647ddae32a8"}
});
{
"_id": "57a52a1be4b0288ba31f1833",
"_createdAt": {
"$date": "2016-08-06T00:06:51.407Z"
}
}
This example shows how to get the ID of the object created:
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var result = Collection.createObject(dbApiKey, "Student", {
"firstName": "James",
"lastName": "Brown",
"isTransferStudent": true,
"courses":[100, 101],
"major": {"name":"Chemistry"},
"toAddress": {"collName": "Address", "_id": "57a52992e4b03647ddae32a8"}
})._id;
Another example with additional data types:
var result = Collection.createObject(dbApiKey, "BigCollection", {
"text": "Hello World",
"number": "1000",
"date": (new Date()).toISOString(),
"array": [1,2,3,4,5],
"object": {"value1":"hello", "value2":"world"},
"location": [40.7128, -74.0059]
});
This example also includes a user session in the createObject method after user login. If you have enabled ACL for this database collection, and set the default ACL to @Creator, then the ACL column will be automatically filled with the current signed in users ID.
var user = DatabaseUser.login(dbApiKey, "amy", "123");
console.log(user.sessionToken);
var result = Collection.createObject(dbApiKey, "Students", {
"firstName": "Anna",
"lastName": "Lee",
"isTransferStudent": false
}, user.sessionToken);
retrieveObject
Collection.retrieveObject(dbApiKey, collectionName, objectId, include [, proj][, token])
Retrieves an object from a specified collection.
Parameters
The method has the following parameters:
dbApiKey
Database API key.
Yes.
token
String with user session token or database master key.
No.
collectionName
String with name of collection.
Yes.
objectId
Unique identifier of the object that should be retrieved.
Yes.
include
Parameter indicated should or shouldn’t include referenced object.
No.
proj
JSON projection object that was built in accordance with the documentation of MongoDB query.
No.
_id
ID of the object created.
columnX
One or more columns from this object.
_createdAt
Date when the object was created.
_updatedAt
Date when the object was updated.
{
"_id":<object_id>,
"column1":"value1",
"column2":"value2",
"_createdAt":{"$date":<create_date>},
"_updatedAt":{"$date":<update>}
}
Examples
Retrieving an object with ID 57928860e4b00ef864f3dc24. The collection has six columns:
- firstName (String)
- lastName (String).
- courses (Array).
- isTransferStudent (Boolean).
- Major (Object).
- toAddress (Pointer to Address collection).
var dbApiKey = "57928860e4b00ef864f3dc24"
var result = Collection.retrieveObject(dbApiKey, "Student", "57a51664e4b03647ddae3294");
{
"courses": [
100,
200,
202
],
"lastName": "Lee",
"firstName": "Anna",
"_createdAt": {
"$date": "2016-08-05T23:56:06.051Z"
},
"_id": "57a52796e4b03647ddae32a5",
"major": {
"name": "Computer Science"
},
"toAddress": {
"collName": "Address",
"_id": "57a5199be4b03647ddae3297"
},
"isTransferStudent": false,
"_updatedAt": {
"$date": "2016-08-05T23:58:39.891Z"
}
}
In this example the referenced collection (Address) data is also retrieved:
var dbApiKey = "57928860e4b00ef864f3dc24"
var result = Collection.retrieveObject(dbApiKey, "Student", "57a51664e4b03647ddae3294", "toAddress");
{
"_createdAt": {
"$date": "2016-08-05T23:56:06.051Z"
},
"courses": [
100,
200,
202
],
"toAddress": {
"City": "Los Angeles",
"_updatedAt": {
"$date": "2016-08-05T22:56:32.455Z"
},
"_id": "57a5199be4b03647ddae3297",
"_createdAt": {
"$date": "2016-08-05T22:56:27.746Z"
},
"Street": "123 Main street"
},
"lastName": "Lee",
"firstName": "Anna",
"_updatedAt": {
"$date": "2016-08-05T23:58:39.891Z"
},
"_id": "57a52796e4b03647ddae32a5",
"major": {
"name": "Computer Science"
},
"isTransferStudent": false
}
DatabaseUser
Database user API.
DatabaseUser provides integration with the Users collection from the database (sign up, log in, log out, update, retrieve and delete users).
Method summary
DatabaseUser has the following methods:
login(dbId, userName, password[, masterKey])
Logs in to the database and gets a session token for next actions.
logout(dbId, token)
Logs out from the database and destroys current session token.
signUp(dbId, userJSON)
Signs up user to the database.
update(dbId, objectId, userJSON[,token])
Updates info about the user in the database.
retrieve(dbId, objectId, include[,token])
Retrieves info about the user in the database.
remove(dbId, objectId[, token])
Deletes the user from the database.
query(dbId, params[, token])
Queries users from the database.
logout
DatabaseUser.logout(dbId, token)
Logs a user out from the database and removes the user session token. This session token will no longer be valid to make any API requests. The method returns no response.
Parameters
The method has the following parameters:
dbApiKey
String with database API key.
Yes.
token
String with user token.
Yes.
var dbApiKey = "57928860e4b00ef864f3dc24"
var username = "amy";
var password = "123";
var token = DatabaseUser.login(dbApiKey, username, password).sessionToken;
DatabaseUser.logout(dbApiKey, token);
update
DatabaseUser.update(dbId, objectId, userJSON[,token])
Updates information about the user in the database.
Parameters
This method has the following parameters:
dbId
String with database ID.
token
String with user token (optional).
objectId
Unique identifier of the user that should be updated.
userJSON
User JSON object.
{
"username":<username>,
"_createdAt":<datetime>,
"_updatedAt":<datetime>,
"_id":<user_id>
}
var dbId = "52776916a044652b54f1f976";
var username = "testUser10";
var password = "testUser10";
var id = DatabaseUser.signUp(dbId, {
"username": username,
"password": password
})._id;
var token = DatabaseUser.login(dbId, username, password).sessionToken;
var updated = DatabaseUser.update(dbId, id, {
"username": "testUserNew",
"password": "testUserNew"
}, token);
retrieve
DatabaseUser.retrieve(dbId, objectId, include[,token])
dbId
String with database id.
token
String with user token.
objectId
Unique identifier of the user that should be updated.
include
Parameter that indicates whether the referenced object should be included.
{
"username":<username>,
"_createdAt":<datetime>,
"_updatedAt":<datetime>,
"_id":<user_id>
}
var dbId = "52776916a044652b54f1f976";
var username = "testUser10";
var password = "testUser10";
var token = DatabaseUser.login(dbId, username, password).sessionToken;
var user = DatabaseUser.retrieve(dbId, id, null, token);
signUp
DatabaseUser.signUp(dbApiKey, userJSON)
Sings up a user. This method will create a new record in the Users collection. The username value has to be unique.
Parameters
The method has the following parameters:
dbApiKey
String with database API key.
Yes.
userJSON
User JSON object. This object holds username, password and any additional data.
Yes.
Response
The method has the following response. If the Users collection has additional custom columns, those columns will be returned as well.
{
"username":<username>,
"_createdAt":<datetime>,
"_updatedAt":<datetime>,
"_id":<user_id>,
"sessionToken":<session_token>
}
Examples
Basic Signup
This example shows how to sign up (register) a user with just the username and password. This the minimum information you have to provide to create a new user.
var dbApiKey = "57928860e4b00ef864f3dc24"
var username = "amy";
var password = "123";
var user = DatabaseUser.signUp(dbApiKey, {
"username": "monica",
"password": "123"
});
Apperyio.response.success(user, "application/json");
{
"_createdAt": {
"$date": "2016-08-10T23:02:51.711Z"
},
"sessionToken": "01a1a4e8-1b4d-4f56-8439-7386a2806235",
"_id": "57abb29be4b05ed524a72a4b",
"username": "alex",
"_updatedAt": {
"$date": "2016-08-10T23:02:51.713Z"
}
}
Signup with Additional Information
This examples includes additional information (Notes and isActive columns) that are present in the Users collection:
var dbApiKey = "57928860e4b00ef864f3dc24"
var username = "amy";
var password = "123";
var user = DatabaseUser.signUp(dbApiKey, {
"username": "alex",
"password": "123",
"Notes": "A user just craeted",
"isActive": true
});
Apperyio.response.success(user, "application/json");
{
"_updatedAt": {
"$date": "2016-08-10T23:04:57.565Z"
},
"_createdAt": {
"$date": "2016-08-10T23:04:57.563Z"
},
"_id": "57abb319e4b08e80b78ec571",
"username": "alex",
"Notes": "A user just craeted",
"isActive": true,
"sessionToken": "57ff6c4c-6601-4460-b01d-7db3be0c65a9"
}
login
DatabaseUser.login(dbApiKey, username, password[, masterApiKey])
Logs a user into the database, returns a session token which is then used to invoke other APIs.
Parameters
This method has the following parameters:
dbApiKey
String with database API key.
Yes.
username
String with user username.
Yes.
password
String with user password.
Yes.
masterKey
String with database master key, if specified than the password value is ignored.
No.
{
"_id": <some_id>,
"sessionToken": <session_token>
}
var dbApiKey = "57928860e4b00ef864f3dc24"
var username = "amy";
var password = "123";
var result = DatabaseUser.login(dbApiKey, username, password);
Apperyio.response.success(result, "application/json");
{
"sessionToken": "5220005e-7a53-4200-9dcc-0156b9793be0",
"_id": "5797dfd5e4b0264ccd2efde6"
}
var token = DatabaseUser.login(dbApiKey, username, password).sessionToken;
var dbApiKey = "57928860e4b00ef864f3dc24"
var masterKey = "590e43a0-d15e-4f24-a944-8f30d914ca8f";
var username = "amy";
var password = "123";
var token = DatabaseUser.login(dbApiKey, username, null, masterKey).sessionToken;
Using the Master Key
The Master key gives you admin access to the database. This means you can view, edit and delete any data. Use it only when necessary.
query
DatabaseUser.query(dbId, params[, token])
dbId
String with database id.
token
String with user token.
params
JSON object that contains request parameters.
JSON object params has the following structure:
{
["criteria":<criteria>,]
["skip":<skip>, ]
["limit":<limit>, ]
["count":<count>, ]
["sort":<sort>, ]
["include":<include> ]
}
params JSON parameters:
criteria
JSON
Query object built in accordance with the mongo querying.
skip
integer
Parameter indicating how much objects should be skipped before including objects into response.
limit
integer
Parameter indicating how many objects should be included in response.
count
boolean
Parameter indicating whether the number of selected objects should be included in response.
sort
string
List of fields names split by comma that indicates the order of objects in response.
include
string
Parameter that indicates whether the referenced object should be included.
[{
"username": <username > ,
"_createdAt": <datetime > ,
"_updatedAt": <datetime > ,
"_id": <user_id >
}, ]
var dbId = "52776916a044652b54f1f976";
var username = "testUser10";
var password = "testUser10";
var token = DatabaseUser.login(dbId, username, password).sessionToken;
var query = DatabaseUser.query(dbId, {
"skip": 1,
"limit": 1
}, token);
remove
DatabaseUser.remove(dbApiKey, objectId[, token])
Deletes a user from the database. On successful remove the method returns code 200 and empty body.
Instead of user session token you can provide the Master key to delete any user.
Parameters
The method has the following parameters:
dbApiKey
String with database API key.
Yes.
token
String with user token or Master key.
Yes.
objectId
Unique identifier (ID) of the user that should be deleted.
Yes.
Push Notifications
Push Notifications API.
Used to send Push Notification messages.
Method summary
Push Notifications has the following methods:
send(pushApiKey, messageData)
Sends push notifications.
listScheduled(pushAPIKey)
Returns the list of scheduled push notifications that haven’t already been sent.
deleteScheduled(pushID)
Deletes scheduled push that hasn’t been already sent. In other case it returns an error.
send
PushNotification.send(pushAPIKey, messageData)
Apperyio.PN.send("ffbe3bb4-3ea0-4ee6-b9db-587e43cfdb31", {
payload: {
"message": "Notification sample",
},
});
The following examples send a Push Notification to all devices and also includes custom data:
Apperyio.PN.send("ffbe3bb4-3ea0-4ee6-b9db-587e43cfdb31", {
payload: {
"message": "Notification sample",
"customData": {"name1":"value1", "name2":"value2"}
},
});
The following example sends push notifications to the devices using channels. Badge (iOS parameter only) is specified.
Apperyio.PN.send("ffbe3bb4-3ea0-4ee6-b9db-587e43cfdb31", {
payload: {
"message": "Notification sample",
"badge": 1
},
filter: {"channels": {"$in":[1,2]}},
schedule: {
scheduledTime: 1484870400000,
// Use timeZone or userDeviceTimeZone but not both
timeZone: 120
//useDeviceTimeZone:true
}
});
listScheduled
PushNotifications.listScheduled(pushAPIKey)
deleteScheduled
PushNotifications.deleteScheduled(Push_id)
Request
Request API.
keys()
Lists provided URL parameter names.
get(name)
Gets URL parameter with specified name.name – string.
has(name)
Signals whether URL parameter with specified name exists in request.name – string.
body()
Returns request body or null for GET requests.
mimeType()
Returns body mimetype or null for GET requests.
header(name)
Returns the first value of the specified header, if exists
object()
Returns parsed request body object for requests with body mime types of "application/x-www-form-urlencoded" or "application/json"
headers
JSON object – provides header values
params
JSON object – provides URL parameters.
user
JSON object – provides information about the logged user.
method
String – name of request method (GET or POST).
Example
Let's say we have added following requests parameters:
Db_id = 51bf5ec1975a2d55263801cd, collection = books.
And we added the request body data string: "some useful information".
Your URL will look like this:
https://api.<appery.domain>/rest/1/code/<scriptGUID>/exec?Db_id=51bf5ec1975a2d55263801cd&collection=books
// Echo service: replies with specified parameters
var responseBody = {},
requestParams = {},
paramKeys = Apperyio.request.keys(); // returns array of request parameters ["Db_id", "collection"]
for (var key = 0; key < paramKeys.length; key++) {
requestParams[paramKeys[key]] = Apperyio.request.get(paramKeys[key]); // returns value of request parameter by its name
}
responseBody.requestBody = Apperyio.request.body(); // responseBody.requestBody now contains "some useful information"
responseBody.requestParams = requestParams; // responseBody.requestParams now contains object { "DB_id": "51bf5ec1975a2d55263801cd", "collection": "books" }
responseBody.method = method; // responseBody.method now contains string "GET" or "POST".
Apperyio.response.success(responseBody, "application/json");
mimeType
request.mimeType()
Returns the MIME type (content type) of a POST request. Returns null for a GET request.
This examples shows a script prints the MIME type of a POST request. The request body is in JSON format.
{
"email":"james@appery.io",
"title": "Engineer",
"location": "Barcelona"
}
console.log(request.mimeType());
application/json
get
Request.get(name)
keys
request.keys()
body
request.body()
Returns a request body for POST request or null for a GET.
This examples shows a script that read the request body.
{
"email":"james@appery.io",
"title": "Engineer",
"location": "Barcelona"
}
var body = request.body();
console.log(body);
{
"email":"james@appery.io",
"title": "Engineer",
"location": "Barcelona"
}
Response
Response API.
success()
Returns successful response without body.
success(body)
Returns successful response with specified body.
success(body, mimeType)
Returns successful response with specified body and MIME type.
binary(body)
Returns successful response with binary data in body and MIME type “application/octet-stream.”
binary(body, mimeType)
Returns successful response with binary data in body and specified MIME type.
redirect(url)
Returns redirect response with specified location URL.
error(body)
Returns error response with specified body and error code (response status).
setHeader(name, value)
Sets specified header value.
binary
response.binary(body, mimeType)
Returns a successful binary response with optional MIME type.
Parameters:
The method has the following parameters:
body
Array of bytes (represented by integer numbers in range 0-255).
mimeType
Optional. Any binary MIME type, for example:
- application/zip
- application/pdf
- image/jpeg
try {
// Binary data
response.binary([80, 75, 5, 6, 0, 0]);
} catch (e) {
// Redirect to error page
response.redirect("http://error.page.com");
}
UEsFBgAA
var secureCode = request.get("secureCode");
if (validateCode(secureCode)) {
try {
// Send binary data
response.binary([80, 75, 5, 6, 0, 0], "application/zip");
} catch (e) {
// Redirect to error page
response.redirect("http://error.page.com");
}
} else {
// Respond with error message and code
response.error("Secure code is not valid", "Unauthorized"); //It's possible to use error code instead of its name
//response.error("Cannot find an article", 401) //Works the same
}
Error code SCSE014: Script execution failed. Details have been added to Trace tab.
redirect
response.redirect(url)
Example
This examples shows how to redirect to http://google.com.
error
response.error(body)
Returns an error response with a specified body and error code (HTTP response status).
Parameters
The method has the following parameters
body
Response body as string, number, boolean, array, object.
code
HTTP error code (string or number). More information.
response.error("Security code is not valid", 401);
Security code is not valid
401
success
response.success(body, mimeType)
var email = request.get("email");
var title = request.get("title");
var location = request.get("location");
// Script logic
// Emtpy response with HTTP status code 200
Apperyio.response.success();
// HTTP status code: 200
// MIME type: */*
Example
Successful response with body. This examples assumes there are three request parameters:
- title
- location
var email = request.get("email");
var title = request.get("title");
var location = request.get("location");
var res = {"email":email, "title":title, "location":location};
Apperyio.response.success(res);
// HTTP status code: 200
// MIME type: */*
{
"email": "james@appery.io",
"location": "Barcelona",
"title": "Engineer"
}
Example
Successful response with body and MIME type. This examples assumes there are three request parameters:
- title
- location
var email = request.get("email");
var title = request.get("title");
var location = request.get("location");
var res = {"email":email, "title":title, "location":location};
Apperyio.response.success(res, "application/json");
// HTTP status code: 200
// MIME type: application/json
{
"email": "james@appery.io",
"location": "Barcelona",
"title": "Engineer"
}
XHR
XHR API.
Used to send HTTP requests to a web server and retrieve any type of data directly back into the script.
Two implementations are available XHR2 and XHR. We recommend to use XHR2 as it is a newer implementation, faster, and supports additional HTTP methods.
Method summary
XHR has the following method:
send(method, url, options)
Makes synchronous HTTP requests.
send
XHR2.send(method, url, options)
Makes synchronous HTTP requests to a web server and retrieve any type of data directly back into the script.
Parameters Summary
This method has the following parameters:
method
HTTP method name.
- XHR2 supports the following methods:
- DELETE
- GET
- POST
- PUT
- HEAD
- OPTIONS
- TRACE
- XHR supports the following methods:
- DELETE
- GET
- POST
- PUT
url
String with resource URL.
options
JSON object with additional request parameters. The options are:
- parameters – JSON object with query request parameters. They will be added to the URL.
- headers – JSON object with request headers.
- body – string or JSON object with request body. It can be byte array if isRawRequest is set to true.
- isRawRequest – if request body is binary data (optional). Default value is false.
- isRawResponse – if response body is binary data (optional). Default value is false.
{
"status" : <response_status>,
"headers" : {
[ <header1> : <value1>, ]
[ <header2> : <value2>, ]
},
"body" : <response_body>
}
Response has the following parameters:
status
HTTP response status code.
headers
JSON object with response headers.
body
String with response body. It can be JSON object if value of header Content-Type is application/json and response body is a valid JSON object. It can be byte array if isRawResponse is set to true.
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
var response = XHR2.send("GET", url, {});
console.log(response);
{
status: 200,
headers: {
'x-frame-options': 'SAMEORIGIN',
'content-type': 'application/json; charset=UTF-8',
'cache-control': 'public, max-age=86400',
'x-xss-protection': '1; mode=block',
expires: 'Thu, 14 Jul 2016 20:52:11 GMT',
'access-control-allow-origin': '*',
'content-length': 527,
server: 'mafe',
'content-encoding': 'gzip',
date: 'Wed, 13 Jul 2016 20:52:11 GMT',
vary: 'Accept-Language'
},
body: '{\n "results" : [\n {\n "address_components" : [\n {\n "long_name" : "1600",\n "short_name" : "1600",\n "types" : [ "street_number" ]\n },\n {\n "long_name" : "Amphitheatre Parkway",\n "short_name" : "Amphitheatre Pkwy",\n "types" : [ "route" ]\n },\n {\n "long_name" : "Mountain View",\n "short_name" : "Mountain View",\n "types" : [ "locality", "political" ]\n },\n {\n "long_name" : "Santa Clara County",\n "short_name" : "Santa Clara County",\n "types" : [ "administrative_area_level_2", "political" ]\n },\n {\n "long_name" : "California",\n "short_name" : "CA",\n "types" : [ "administrative_area_level_1", "political" ]\n },\n {\n "long_name" : "United States",\n "short_name" : "US",\n "types" : [ "country", "political" ]\n },\n {\n "long_name" : "94043",\n "short_name" : "94043",\n "types" : [ "postal_code" ]\n }\n ],\n "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",\n "geometry" : {\n "location" : {\n "lat" : 37.422364,\n "lng" : -122.084364\n },\n "location_type" : "ROOFTOP",\n "viewport" : {\n "northeast" : {\n "lat" : 37.4237129802915,\n "lng" : -122.0830150197085\n },\n "southwest" : {\n "lat" : 37.42101501970851,\n "lng" : -122.0857129802915\n }\n }\n },\n "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",\n "types" : [ "street_address" ]\n }\n ],\n "status" : "OK"\n}\n'
}
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
var response = XHR2.send("GET", url, {});
console.log(response.body);
{
"results": [{
"address_components": [{
"long_name": "1600",
"short_name": "1600",
"types": ["street_number"]
}, {
"long_name": "Amphitheatre Parkway",
"short_name": "Amphitheatre Pkwy",
"types": ["route"]
}, {
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": ["locality", "political"]
}, {
"long_name": "Santa Clara County",
"short_name": "Santa Clara County",
"types": ["administrative_area_level_2", "political"]
}, {
"long_name": "California",
"short_name": "CA",
"types": ["administrative_area_level_1", "political"]
}, {
"long_name": "United States",
"short_name": "US",
"types": ["country", "political"]
}, {
"long_name": "94043",
"short_name": "94043",
"types": ["postal_code"]
}],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry": {
"location": {
"lat": 37.422364,
"lng": -122.084364
},
"location_type": "ROOFTOP",
"viewport": {
"northeast": {
"lat": 37.4237129802915,
"lng": -122.0830150197085
},
"southwest": {
"lat": 37.42101501970851,
"lng": -122.0857129802915
}
}
},
"place_id": "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types": ["street_address"]
}],
"status": "OK"
}
Request with Basic Authentication
This example shows invoking an API that uses Basic Authentication. Basic Authentication usually has this form: http://username@password@host.com. To invoke this from a script add the Authorization header. The username@password encoding can be done using browser's console by running this code: window.btoa("username@password");.
var url = "https://host.com/service"; // REST API URL
var XHRResponse = XHR2.send("GET", url, {
"headers": {
"Authorization": "Basic <encoded_string>"
}
});
Apperyio.response.success(XHRResponse.body, "application/json");
// Mailgun domain in the form: sandbox123abc.mailgun.org
var domain = "sandbox123abc.mailgun.org";
// Mailgun endpiont to send an email message
var url = "https://api.mailgun.net/v3/"+domain+"/messages";
var from = "Excited User <user@yourdomain.io>";
var to = request.get("to");
var subject = request.get("subject");
var text = request.get("text");
var XHRResponse = XHR2.send("POST", url, {
"parameters": {
"from" : from,
"to" : to,
"subject": subject,
"text": text
},
"headers": {
"Authorization": "Basic YXBpOmtleS0wY2UxNDM5ZGJiNjczOQ==") // For API key, see Mailgun domains page: https://mailgun.com/app/domains
}
});
Apperyio.response.success(XHRResponse.body, "application/json");
{
"message": "Queued. Thank you.",
"id": "<20160713210709.24932.84860.9931A6A8@sandbox123abc.mailgun.org>"
}
Invoking an API Express Service
This examples show invoking an API Express service that dost a POST and its body is set to JSON such as {"param1": num}.
var url = "https://api.appery.io/rest/1/apiexpress/api/test/me?apiKey=.....";
var XHRResponse = XHR2.send("POST", url, {
"headers": {
"Content-Type": "application/json"
},
"body": {"param1" : 45}
});
Apperyio.response.success(XHRResponse.body, "application/json");
ScriptCall
ScriptCall API.
call
ScriptCall.call(scriptID, params, body, bodyMimeType)
scriptID
ID of the script to invoke. Script alias can be specified instead of ID.
params
Parameters to pass to the script. In JSON format.
body
Body content to pass to the script.
bodyMimeType
Content type of the body parameter.
var greeting = request.get("greeting");
var person = request.get("person");
var hello = greeting + ", " + person;
// request.body is read and passed back to the calling script.
Apperyio.response.success({"msg":greeting, "info":request.body()}, "application/json");
// Invoke Script #1
var result = ScriptCall.call("55d4c897-4cea-57ab-800b-473f74e5885a", {"greeting":"Hello", "person":"Jenny"}, "A greeting script - nice.", "plain/text");
Apperyio.response.success(result.body, "application/json");
{
"msg": "Hello",
"info": "A greeting script - nice."
}
In Memory Data (IMD)
IMD API.
Allows you to store data in fast memory for 20 minutes. It works like a very fast cache. Storing data in the In Memory Data is a lot faster than storing data a database collection. Here are a few examples In Memory Data can be used for:
- Storing a temporary token that will expire within 20 minutes.
- Storing a temporary password that will expire within 20 minutes.
- Any app temporary app data which requires very fast access.
Method summary
put(key, value)
Inserts a specified value with a specified key into In Memory Data (cache). Both key (max. length 64 chars) and value (max. length 255 chars) must be strings.
get(key)
Returns a value specified by a key, or null if the cache contains no such key.
remove(key)
Removes the key/value if such key is present in In Memory Data (cache).
contains(key)
Returns true if the cache contains a value with such key.
length()
Returns the number of key-value pairs in In Memory Data (cache).
keys()
Returns an array of the keys contained in In Memory Data (cache).
remove
IMD.remove(key)
keys
IMD.keys()
length
IMD.length()
contains
IMD.contains(key)
Returns true if the cache contains a value with the specified key. Otherwise returns false.
Paramaters
The method has the following parameters:
key
Key for which to check if the value is stored in the cache.
Error Handling: Try-Catch
It's a good practice to put code that can throw an exception inside try.. catch block. This is a general good practice and not specific to Appery.io Server Code. Learn more about JavaScript try-catch.
The following code shows an example of try...catch block when updating a user in the database:
try{
var user = DatabaseUser.update(
db_id,
user_id,
{"username":username,"email": email},
userToken
);
} catch(e){
Apperyio.response.error(
{error: e.toString()},
"application/json"
);
}
Error Responses
Server Code error responses.
Collection
Error responses for Collection methods.
getCollectionList
The method may return the following error messages:
401
DBSL001
Unauthorized.
403
DBSL003
You do not have permission to access the specified database.
404
DBSL014
Database with id='dbApiKey’ does not exist.
401
DBPL001
Authorized
403
DBPL003
You do not have permission to access specified database.
404
DBPL014
Database with id='<database_id>’ does not exist.
404
DBPL207
Metadata doesn’t contain collection with id='<database_id>’.
400
BPL209
Invalid collection ID: id='<database_id>’.
401
DBSG001
Unauthorized
400
DBSG002
Invalid session token specified.
403
DBSG003
You do not have permission to access specified database.
404
DBSG014
Database with id='<database_id>’ does not exist.
404
DBSG203
Collection ‘<collection_name>’ absent in database with id ‘<database_id>’.
403
DBSG201
Collection doesn’t have READ permission.
404
DBSG204
Collection with id <collection_id> does not exist
404
DBSG205
Collection ‘<collection_name>’ doesn’t contain object with id <object_id>.
400
DBSG210
Invalid object ID: ‘<object_id>’.
400
DBSG263
Incorrect projection
400
DBSG237
The column you are trying to include does not exist:
400
DBSG238
The column you are trying to include is not of the Pointer type:
400
DBSG239
Error including more than 10 levels of pointer values.
403
DBSG254
You don’t have permission to access system collections.
400
DBSG264
Mongo error: error code is: ‘%s’.
400
DBSG265
Mongo error
403
DBSG333
Access denied: you don’t have %s permission on specified object
400
DBSU002
Invalid session token specified.
404
DBSU014
Database with id='<database_id>’ does not exist.
403
DBSU020
Using reserved database name ‘tiggzi-iods’ is forbidden.
403
DBSU202
Collection doesn’t have WRITE permission.
404
DBSU203
Collection ‘<collection_name>’ absent in database with id ‘<database_id>’.
404
DBSU205
Collection ‘<collection_name>’ doesn’t contain object with id <object_id>.
404
DBSU207
Metadata doesn’t contain collection with id=<collection_id>.
400
DBSU210
Invalid object ID: ‘<object_id>’.
400
DBSU234
Creation and modification objects with system fields not allowed.
400
DBSU211
must have unique value
400
DBSU212
cannot be null.
400
DBSU213
Field ‘<field_name>’ already present.
400
DBSU217
Index does not allow fields with non-unique values.
400
DBSU218
Invalid object: <object>.
400
DBSU221
Cannot set value of type Object to Array column. Possibly ‘__op’ field is missing.
400
DBSU222
Cannot set value of type Object to Array column. Possibly ‘objects’ field is missing.
400
DBSU223
‘__op’ field must have a String value
400
DBSU224
‘__op’ field must have a non-empty String value
400
DBSU225
'objects’ field must have an Array value.
400
DBSU226
‘objects’ field must have a non-empty String value.
400
DBSU227
Unknown operation ‘<operation_name>’
400
DBSU229
Unknown type in metaData='<type>’ with value='<value>’.
400
DBSU230
Date value should be in format “yyyy-mm-dd” : ‘<value>’.
400
DBSU231
‘<pointer_column_name>’ is missing for pointer column ‘<collumn_name>’.
400
DBSU232
Incoming object contain control attribute(s): <list_attributes>. Its usage is forbidden.
400
DBSU241
Pointer column value of field ‘<field_name>’ must be JSON object but has ‘<actual_type>’.
400
DBSU245
Incorrect field: ‘<field_name>’ of object.
400
DBSU252
Invalid value for type ‘<type>: ‘<value>’.
400
DBSU246
GeoPoint should be an array longitude, latitude of values in [ -180, 180 ].
403
DBSU254
You don’t have permission to access system collections.
403
DBSU255
Invalid collection name for pointer field '<actual>’. Expected ‘<expected>’.
403
DBSU333
Access denied: you don’t have <read|write> permission on specified object.
400
DBSP002
Invalid session token specified
404
DBSP014
Database with id='<database_id>’ does not exist.
403
DBSP020
Using reserved database name ‘tiggzi-iods’ is forbidden.
403
DBSP202
Collection doesn’t have WRITE permission.
404
DBSP203
Collection ‘<collection_name>’ absent in database with id ‘<database_id>’.
404
DBSP207
Metadata doesn’t contain collection with id=<collection_id>.
400
DBSP234
Creating or editing system columns in an object is not allowed. System column name starts with underscore ( _).
400
DBSP211
Field ‘<field_name>’ must have unique value
400
DBSP212
Field ‘<field_name>’ cannot be null
400
DBSP217
Index does not allow fields with non-unique values
400
DBSP219
Incorrect query
400
DBSP221
Cannot set value of type Object to Array column. Possibly ‘__op’ field is missing.
400
DBSP222
Cannot set value of type Object to Array column. Possibly ‘objects’ field is missing.
400
DBSP223
‘__op’ field must have a String value.
400
DBSP224
‘__op’ field must have a non-empty String value
400
DBSP225
‘objects’ field must have an Array value
400
DBSP226
'objects’ field must have a non-empty String value.
400
DBSP227
Unknown operation ‘<operation_name>’
400
DBSP229
Unknown type in metaData='<type>’ with value='<value>’
400
DBSP230
Date value should be in fomat “yyyy-mm-dd” : ‘<value>’
400
DBSP231
‘<pointer_column_name>’ is missing for pointer column ‘<collumn_name>’.
400
DBSP232
Incoming object contain control attribute(s): <list_attributes>. Its usage is forbidden.
400
DBSP236
Collection name contains invalid character.
400
DBSP241
Pointer column value of field ‘<field_name>’ must be JSON object but has ‘<actual_type>’.
400
DBSP245
Incorrect field: ‘<field_name>’ of object.
400
DBSP248
Value of ‘<$maxDistanceInKilometers|$maxDistanceInMiles|$maxDistanceInRadians>’ should be a number.
400
DBSP249
Geospatial query should include only 1 GeoPoint field at a time.
400
DBSP250
$and expression must be a nonempty array.
400
DBSP252
Invalid value for type ‘<type>’: ‘<value>’.
400
DBSP246
GeoPoint should be an array longitude, latitude of values in [ -180, 180 ].
403
DBSP254
You don’t have permission to access system collections.
400
DBSP255
Invalid collection name for pointer field <actual>’. Expected ‘<expected>’.
400
DBSP601
Native operations object must be present.
400
DBSP602
Native operation works on fields with following types: number, string, boolean, date.
400
DBSP603
Operations $inc and $mul works only on fields with number type.
400
DBSP604
Operations $min and $max works only on fields with number or date types.
400
DBSP605
Field ‘<field_name>’ absent in collection structure.
400
DBSM606
Update or operations object must be present (this error message visible only from sc-collection-api).
400
DBSM607
Invalid update object: <object> (this error message visible only from sc-collection-api).
400
DBSM608
Invalid operations object: <object> (this error message visible only from sc-collection-api).
400
DBSD002
Invalid session token specified.
404
DBSD014
Database with id='<database_id>’ does not exist.
403
DBSD020
Using reserved database name ‘tiggzi-iods’ is forbidden.
403
DBSD201
Collection doesn’t have READ permission.
403
DBSD202
Collection doesn’t have WRITE permission.
404
DBSD203
Collection ‘<collection_name>’ absent in database with id ‘<database_id>’.
404
DBSD205
Collection ‘<collection_name>’ doesn’t contain object with id <object_id>.
404
DBSD207
Metadata doesn’t contain collection with id=<collection_id>.
403
DBSD254
You don’t have permission to access system collections.
403
DBSD333
Access denied: you don’t have <read|write> permission on specified object.
##query
400
DBSQ002
Invalid session token specified.
404
DBSQ014
Database with id='<database_id>’ does not exist.
400
DBSQ236
Collection name contains invalid character.
404
DBSQ207
Metadata doesn’t contain collection with id=<collection_id>.
400
DBSQ219
Incorrect query.
400
DBSQ263
Incorrect projection.
400
DBSQ240
Wrong URL parameter ‘<skip|limit>’ with value ‘<value>’, cause: <description_reason>.
400
DBSQ237
The column you are trying to include does not exist: ‘<column_name>’.
400
DBSQ238
The column you are trying to include is not of the Pointer type: ‘<another_type>’.
400
DBSQ239
Error including more than 10 levels of pointer values.
400
DBSQ248
Value of ‘<$maxDistanceInKilometers|$maxDistanceInMiles|$maxDistanceInRadians>’ should be a number.
400
DBSQ249
Geospatial query should include only 1 GeoPoint field at a time.
400
DBSQ250
$and expression must be a nonempty array.
404
DBSQ203
Collection ‘<collection_id>’ absent in database with id ‘<database_id>’.
403
DBSQ201
Collection doesn’t have READ permission.
403
DBSQ254
You don’t have permission to access system collections.
400
DBSQ264
Mongo error: error code is ‘%s’
400
DBSQ265
Mongo error: ‘%s’
400
DBSV002
Invalid session token specified.
404
DBSV014
Database with id='<database_id>’ does not exist.
400
DBSV219
Incorrect query.
400
DBSV237
The column you are trying to include does not exist: ‘<column_name>’.
400
DBSV248
Value of ‘<$maxDistanceInKilometers|$maxDistanceInMiles|$maxDistanceInRadians>’ should be a number.
400
DBSV249
Geospatial query should include only 1 GeoPoint field at a time.
400
DBSV250
$and expression must be a nonempty array.
404
DBSV203
Collection ‘<collection_name>’ absent in database with id ‘<database_id>'.
403
DBSV201
Collection doesn’t have READ permission.
403
DBSV254
You don’t have permission to access system collections.
404
DBUI014
Database with id='<database_id>’ does not exist.
400
DBUI106
User name must be present.
400
DBUI107
User password must be present.
404
DBUI110
User ‘%s’ does not exist.
400
DBUI112
Login with wrong password.
400
DBUI021
Master Key should not be empty (error present only in server code databaseUser api).
400
DBUI510
Login with wrong master key (error present only in server code databaseUser api).
401
DBUO001
Unauthorized
400
DBUO002
Invalid session token specified.
403
DBUO003
Forbidden
404
DBUO014
Database with id='<database_id>’ does not exist.
404
DBUS014
Database with id='<database_id>’ does not exist.
400
DBUS101
New user must not have ‘_id’ field.
400
DBUS102
New user must have name.
400
DBUS103
New user must have password.
400
DBUS111
User <username> already exists in database.
400
DBUS234
Creation and modification objects with system fields not allowed.
400
DBUS211
Field ‘<field_name>’ must have unique value.
401
DBUU001
Unauthorized
400
DBUU002
Invalid session token specified.
403
DBUU003
Forbidden
404
DBUU014
Database with id='<database_id>’ does not exist.
404
DBUU109
User with id <user_id> absent in database <database_id> .
400
DBUU104
User must be specified and can’t be null or empty.
400
DBUU105
Username can’t be null or empty.
400
DBUU111
User <username> already exists in database.
400
DBUU210
Invalid object ID: ‘<object_id>’.
400
DBUU234
Creation and modification objects with system fields not allowed.
300
DBUU212
Field ‘<field_name>’ cannot be null.
403
DBUU333
Access denied: you don’t have %s permission on specified object.
401
DBUG001
Unauthorized
400
DBUG002
Invalid session token specified.
403
DBUG003
Forbidden
404
DBUG014
Database with id='<database_id>’ does not exist.
404
DBUG108
User with id <user_object_id> is not found.
400
DBUG263
Incorrect projection
401
DBUD001
Unauthorized
400
DBUD002
Invalid session token specified.
403
DBUD003
Forbidden
404
DBUD014
Database with id='<database_id>’ does not exist.
404
DBUD108
User with id <user_object_id> is not found.
401
DBUQ001
unauthorized
400
DBUQ002
Invalid session token specified.
404
DBUQ014
Database with id='<database_id>’ does not exist.
400
DBUQ219
Incorrect query
400
DBUQ263
Incorrect projection
400
DBUQ240
Wrong URL parameter ‘<skip|limit>’ with value ‘<value>’, cause: <description_reason>.
403
DBUQ201
Collection doesn’t have READ permission.
404
PNMM004
Push API Key: <pushAPIKey> not found.
400
PNMM017
Message can’t be empty.
400
PNMM021
Nobody is able to receive this message.
400
PNMM056
Database with id='<db_id>’ is not connected to push application
400
PNMM062
Badge cannot be negative.
404
PNMM082
iOS Push certificate is not set.
404
PNMM084
Android API key is not set.
404
PNMM085
iOS Push certificate password is not set.
404
PNMM086
Push message length can’t be more then 200 symbols for iOS devices.
404
PNMM087
Push message length can’t be more then 1024 symbols for android devices.
400
PNMM101
Empty scheduled time.
400
PNMM102
Empty time zone.
400
Bad Request
401
Unauthorized
403
Forbidden
404
Not Found
500
Internal Server Error
Error Code
If the code is not specified, or specified incorrectly, 500 (Internal Server Error) will be used.
403
SCSX026
Access denied: only authenticated users can access this script.
400
SCSX049
Script launch number quota reached.
429
SCSX050
Script launch interval time has not elapsed.
404
SCSX010
Script not found.
400
SCSX014
Script execution failed.
400
SCSX018
Script execution timed out.
500
SCSX021
This wasn’t supposed to happen.
400
SCSX022
Specified session token is no longer valid.
404
SCSX047
Script not accessible because accessible property set to false value.
Script-Call-API specific error #16:
Max depth in script API calling reached (to prevent infinite recursion).
SCCS016
Max depth (<maxDepth>) for script calls reached.
053
In memory data max keys quota reached.
054
You can’t save more than %s symbols.
Overview
Push Notifications overview.
Introduction
Appery.io Push Notifications allow you to send notification messages to iOS and Android devices. You can also send targeted messages, for example only to users who subscribed to a particular topic (channel).
The Push Notifications service URL is:
https://api.appery.io/rest/push/[action]
Action Summary
With Appery.io Push Notifications you can perform the following actions:
- Send a Push Notification to all or specific devices.
- Register a device to receive Push Notifications.
- Get device registration information.
- Unregister a device. This will unsubscribe a device from receiving messages.
- Update device registration.
- List scheduled Push Notification messages.
- Remove scheduled Push Notification message.
Sending a Push Notification
Sending a Push Notification mesage.
You can send a Push Notification message to one or more devices (iOS or Android) that installed your app by making a request to the following endpoint:
https://api.appery.io/rest/push/msg
X-Appery-Push-API-Key is a required header for this service, you can find this key in the Settings section in Apps > Push Notifications tab. As this is a POST method service, non-header parameters should be passed as request body.
If the push notification is scheduled the server returns HTTP 200 and a list of the saved push notifications, otherwise the server returns with a HTTP 204 NO CONTENT status, even if no messages were sent or delivered.
X-Appery-Push-API-Key
Header. Unique key issued by server that allows push notifications to be sent.
expirationTime
Time stamp in UTC TZ, when the provider (Apple, Google, etc.) should stop trying to send notification (if device is unavailable).
filter
Parameter used for filtering devices.
options
Object with push notification sending options.
payload
Object that contains text message and badge.
schedule
Object that contains data for scheduling.
status
Indicates sent push notification instantly or schedule.
filter is an optional parameter. With the filter being empty, push notifications will be sent to all devices.
schedule is an optional parameter for immediate push notifications.
404
PNMM004
Master Key: <pushAPIKey> not found
400
PNMM017
Message can’t be empty
400
PNMM021
There are nobody who will be able to receive this message
400
PNMM056
Database with id='<db_id>' is not connected to push application
400
PNMM062
Badge cannot be negative
404
PNMM082
iOS Push certificate is not set
404
PNMM084
Android API key is not set
404
PNMM085
iOS Push certificate password is not set
400
PNMM088
Push notification data is too big
400
PNMM089
Firebase Admin SDK JSON File is not set
400
PNMM101
Empty scheduled time
400
PNMM102
Empty time zone
400
PNMM116
Push notification payload should include at least one of this fields: "message", "title", "custom data"
400
PNMM117
Can't authenticate to Google. Please check Firebase Admin SDK JSON File
400
PNMM960
Specified brand is not valid
Example
This examples show how to send a Push Notification message right away. To send a message right away the status parameter is set to sent.
curl -X POST
-H "X-Appery-Push-API-Key: 2cc37fde-7d34-48ef-a13e-816e9e93ef2d"
-H "Content-Type: application/json"
-d '{
"payload":{
"message":"Hey!",
"badge":1
},
"status":"sent"
}'
https://api.appery.io/rest/push/msg
Payload
Objects that contain text messages and badges.
Parameters
- actionButtons (Android) – a list of objects that represent buttons that will be shown a notification:
- buttonTitle – button text;
- buttonIcon – the image will be shown on the left side of text;
- buttonCallback – the global function of the app. Push objects will be send as an argument.
- badge (iOS) – the number shown with the app icon in iOS, if empty the badge will not be changed on the device.
- color (Android) – the background color of a notification icon is supported on Android 5.0 and greater. Examples of values: red, #001100, #AA00AA.
- contentAvailable (iOS) – if the value is 1, than app will be awakened.
- customData – custom data that will be sent to the device.
- icon (Android) – the main icon of the notification (it will be small, if payload.image is also added). The Image should be put into the ANDROID/project_name/res/drawable/icon_name.png location and the payload.icon should NOT have an extension.
- image (Android) – Is shown as a large icon for Android notifications. This should be added to ANDROID/project_name/res/drawable/icon_name.png location and the payload.image should NOT have an extension. Also, the payload.image can have a link to external resource.
- launchImage – is used as the launch image upon tapping the action button or moving the action slider.
- message – message text.
- sound – the sound file name is to only play when a push arrives, an empty string is to be set for no sound; if not specified, the default sound is played. For iOS, sound file should be added to www/soundFileName.wav location and payload.sound should have extension. For Android, sound file should be put to res/raw/soundFileName.wav location and the payload.sound should have an extension.
- title – title of push notification.
{"message":"Hello!", "badge":"1"}
Filter
Options
Object with push notification sending options.
Parameters
- collapseKey – receives a custom string as a key. If a user’s device offline only the last push notification with the same collapse key will be received.
- dryRun – indicates that this push should be sent or if it is just testing. Native support by FCM. The service is checked from Appery.io side for iOS devices.
- priority – the priority of the message. The value 5 for iOS is interpreted as normal for Android. Value 10 for iOS interpreted as high for Android. Setting to Default (or null in the REST request) will stipulate the default server behaviour according to the service policy (for Apple Push Notification service – 10, for Android OS – normal).
- restrictedPackageName – specifies the package name of the application where the registration tokens must match in order to receive the message.
Schedule
Is when a date is selected for when a push notification should be sent (it is always truncated to the minute). Use this parameter if you don’t want to send notifications instantly.
Parameters
- scheduledTime – sending time in YYYY-MM-DD hh:mm:ss:mss format. Always truncates to minutes (mandatory).
- scheduledTimeInTZ – the same time in the specified timezone; this is calculated on the server automatically.
- timeZone – time offset in minutes that determines your time zone.
- useDeviceTimeZone – Boolean flag that binds the sending time to the device time zone.
{"scheduledTime":"2013-12-13 13:44:00.000","timeZone":"180"}
Status
This parameter can take only the sent value. It can be used instead of the schedule parameter when push notifications should be sent instantly.
The schedule and status are interchangeable parameters. Don’t use the {"status":"sent"} if you want to schedule the sending of your push, otherwise notifications will be send instantly.
{"status":"sent"}
Register Device
Registering a device to receive Push Notification messages.
In order to send a Push Notification message to a device, the device has to register to receive messages. Device registration is done by creating a registration record inside the database Devices built-in collection. Registration is done by making a request to the following endpoint:
https://api.appery.io/rest/push/reg
AppType
App platform type (A – Android, I – iOS). Required.
token
Unique app instance identifier. Required.
deviceId
Unique device identifier. Required .
X-Appery-App-Id
Unique identifier of Appery.io app. The app ID can be found in the App Builder URL. For example: https://appery.io/app/project/***e51a...ad9***/edit. Required.
custom_param_name
Name of custom field in _devices table.
custom_param_value
Value of custom_param_name field.
channels
List of channelId channel identifiers.
400
PNDR002
App ID is not specified
400
PNDR007
Device ID must be a string
400
PNDR008
Token must be a string
400
PNDR009
Channels must be an array
400
PNDR0010
Channel length can’t be more than 256 symbols
400
PNDR0011
Type must be a string
400
PNDR0012
Empty token/registrationID
400
PNDR0013
Type must be A or I
400
PNDR0014
Device ID can’t be more than 256 symbols
400
PNDR0015
Project GUID: <appId> not found
400
PNDR0016
Token can’t be more than 256 symbols
400
PNDR0019
Channel can’t be empty
400
PNDR0022
Empty deviceID
400
PNDR960
Specified brand is not valid
deviceId and token information
The deviceId and token parameters are automatically generated device-side. These values can’t be found anywhere except in the devices collection of the Appery.io database. Information about the device (including the deviceId and token parameters) where the app is installed, will be saved in the devices collection of the selected database as soon as the device is running the app.
curl -X POST
-H "X-Appery-App-ID: e51f973c-aad9-4102-9f39-349c25264277"
-H "Content-Type: application/json"
-d '{
"deviceID":"356843051801093;5879669fa11e863e",
"token":"APA91bGZvocg3LT1sOpTEaW...He-QLxN6nFOFdS1Y77b3cpVBBgxPgRBsYQZRAdOA",
"type":"A",
"channels":[1,3,5],
"category":"paid",
"timeZone":"GMT+03:00"
}'
https://api.appery.io/rest/push/reg
The server returns an HTTP 200 OK status and the registered device identifier, if the device was successfully registered.
Get Device Information
Getting device information.
To get device information from the Devices collection in the database, send a GET request with device ID to the following endpoint:
https://api.appery.io/rest/push/reg/<deviceId>
This service can be used for retrieving information about the device stored in the Devices . The response of this service is JSON, which contains all predefined and user-defined fields of the devices collection. This service can be handy when you need to get the deviceID, check its timeZone, or for any other operation involving device info.
The deviceID can be found in the predefined Devices collection of the Appery.io database.
Note
In the devices collection of the Appery.io database, the deviceID field contains a semicolon. (For libraries 3.0 (JQM) and higher the semicolon is not used.) Replace it with %3B to properly send the request, as shown here:
356062053530044;9ec5fd0c3ade6681 = 356062053530044%3B9ec5fd0c3ade6681
The URL with the device ID at the end looks like:
https://api.appery.io/rest/push/reg/356062053530044%3B9ec5fd0c3ade6681
Parameters
The endpoint supports the following parameters:
deviceId
Unique device identifier. Required.
X-Appery-App-Id
Unique identifier of the Appery.io application. Required.
400
PNDG002
The application ID isn’t specified
404
PNDG006
Device ID: <deviceId> not found
400
PNDG006
Project GUID: <appId> not found
400
PNDG960
Specified brand is not valid
curl -X GET
-H "Content-Type: application/json"
-H "X-Appery-App-Id: e51f973c-aad9-4102-9f39-349c25264277"
https://api.appery.io/rest/push/reg/356062053530044%3B9ec5fd0c3ade6681
Unregister Device
Removing device registration.
To delete (unregister) a device from the database, send a DELETE request to the following endpoint with the device ID:
https://api.appery.io/rest/push/reg/<deviceId>
deviceId
Unique device identifier. Required.
X-Appery-App-Id
Unique identifier of the Appery.io application. Required.
400
PNDD002
App ID not specified
404
PNDD006
Device ID: <deviceId> not found
404 (400)
PNDD015
Project GUID: <appId> not found
400
PNDU960
Specified brand is not valid
curl -X DELETE
-H "Content-Type: application/json"
-H "X-Appery-App-Id: e51f973c-aad9-4102-9f39-349c25264277"
https://api.appery.io/rest/push/reg/356062053530044%3B9ec5fd0c3ade6681
Update Device
To update the device, send a PUT request to the associated URL with the device ID at the end:
https://api.appery.io/rest/push/reg/<deviceId>
The update device service is for updating information about any device stored in the devices collection. This service can be used for updating any collection field. For example, it can be timeZone, channels or category (which is a user-defined field).
Parameters
The endpoint has the following parameters
400
PNDU002
App ID not specified
404
PNDU006
Device ID: <deviceId> not found
404
PNDU015
Project GUID: <appId> not found
400
PNDU960
Specified brand is not valid
Example
The following example shows how to update channels column of the specific device. The channels column of the predefined devices collection has an array type. Any new value for this column must be also sent as an array. Any other parameter can be updated the same way.
The X-Appery-App-Id header is a necessary parameter for this request. Other fields are optional. You can specify any field that exists in the devices collection.
type
Application platform type (A – Android, I – iOS). Required.
token
Unique app instance identifier. Required.
deviceId
Unique device identifier. Required.
X-Appery-App-Id
Unique identifier of Appery.io application. Required.
custom_param_name
Name of custom field in _devices table.
custom_param_value
Value of custom_param_name field.
channels
List of channelId channel identifiers.
curl -X PUT
-H "Content-Type: application/json"
-H "X-Appery-App-Id: e51f973c-aad9-4102-9f39-349c25264277"
-d '{
"channels":[1,2,6]
}'
https://api.appery.io/rest/push/reg/<deviceId>
List Scheduled Push Notification Messages
List scheduled Push Notification messages.
To list scheduled Push Notifications, send a GET request to the associated URL. Result contains only scheduled notifications that hasn’t been already sent.
https://api.appery.io/rest/push/msg
X-Appery-Push-API-Key
Unique key issued by server that allows push notifications to be sent. Required.
400
PNML004
Push API Key: <pushAPIKey> not found
404
PNML056
Database with id='<db_id>’ is not connected to push application
curl -X GET
-H "X-Appery-Push-API-Key:2cc37fde-7d34-48ef-a13e-816e9e93ef2d"
-H "Content-Type: application/json"
https://api.appery.io/rest/push/msg
Remove a Scheduled Push Notification Message
Remove a scheduled Push Notification message.
To delete a scheduled push notification, send a DELETE request to the associated URL. This REST will only remove the scheduled message that hasn’t been already sent. In other case it returns an error.
https://api.appery.io/rest/push/msg/<pushId>
pushId
Unique identifier of push notification. Required.
404
PNMD100
Can’t find scheduled push with id: <pushId>
403
PNMD115
You are not permitted to perform this operation
curl -X DELETE
-H "Content-Type: application/json"
https://api.appery.io/rest/push/msg/<pushId>
Overview
Database REST API overview.
Appery.io provides a cloud database to store app data, such as customers, orders, locations, etc. Your app communicates with this cloud database via an elegantly simple REST API.
The database dashboard is used to manage all aspects of the databases, view and edit the data, run queries, and more.
Appery.io uses MongoDB version 2.6.8-1.
This section contains API request format for all endpoints.
Authentication
Authentication is done via HTTP headers.
X-Appery-Database-Id
This is the database API key (ID). Every request must have this header specified.
X-Appery-Session-Token
Session token after user login or registration. This header is required if your app users the User API and has object permissions set (via ACL).
X-Appery-Master-Key
The master key is like having root access to the database. In other words, the app (client) can read, edit and delete any data in the database. Use carefully and only when needed.
Request Format
For a POST and a PUT request the request body must be JSON, with the Content-Type header set to application/json.
Response Format
A JSON object is the response format for all requests.
An HTTP status code indicates whether the request succeeded or not:
- A 2xx status code indicates success.
- A 4xx status code indicates failure.
When a request fails, the response body is still JSON, but will contain an error message. For example:
{
"code": xxx,convenient to use
"error": "error message"
}
Data Types
Database data types.
The Appery.io Database has the following types.
Date
The Date type value is a string which contains a UTC timestamp stored in ISO 8601 format with millisecond precision: YYYY-MM-DDThh:mm:ss.mmm.
Array
An array value is a list of primitive values, such as: string, number or boolean.
cURL:
curl -X POST
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "Content-Type: application/json"
-d '{"marks": [6,7,3]}'
https://api.appery.io/rest/1/db/collections/students/
Example above will create a new entry in the students collection with marks field type of array.
Pointer
As MongoDB is not a relational database, it can’t perform SQL join operations. Instead, there are pointer types that are used as references to another object. It contains the collection name and _id of the referred-to value. Let’s say that the students collection contains the owner column. That column contains the user ID from the Users collection.
The result of the GET request will look like:
{
"_id":"5278cb0ae4b01085e4b7945f",
"_createdAt":"2013-11-05 10:40:10.400",
"_updatedAt":"2015-06-19 13:36:14.844",
"marks":[
7.0,
6.0,
5.0
],
"studentId":30.0,
"studentName":"Sasha",
"owner":{
"collName":"_users",
"_id":"55841aafe4b04bd7168221e2"
}
}
To read multiple children for a parent, use the following where parameter, where columnName is the name of the column with type=pointer and _id is the referenced object of the todo database:
{"columnName": {"$inQuery" : { "_id": "54da2471e4b0e533414b6115"}}}
The pointer value can be set using a POST command and by passing two parameters – collName and _id of referenced object:
cURL:
curl -X POST
-H "X-Appery-Database-Id: 542416a1e4b0b7fdcc764eb0"
-H "Content-Type: application/json"
-d '{"owner": {"collName":"_users", "_id":"5540ed6ae4b020ea2fabaf44"}}'
https://api.appery.io/rest/1/db/collections/students/
Example above will create a new entry in the students collection with owner field type of pointer.
To retrieve the referenced object value (not a pointer value) use the include parameter.
Example
This example shows how to use Server Code script and Pointer data type to setup user registration – Learn How to Create a User Registration Form with the Appery.io Database and Server Code .
Object
Object type is a general representation of a JSON object, which can have any structure. When an object with object type is given, the column value is specified as a JSON object in { } brackets. Object type also supports querying.
Note
Read more about querying.
GeoPoint
The Geopoint type is used to define a geographic location with longitude and latitude, and presented as an array of two values.
Please mind that longitude goes first!
We are using 2dsphere indexes for Geopoint: https://docs.mongodb.com/v3.2/geospatial-queries/#legacy-coordinate-pairs
cURL:
curl -X POST
-H "X-Appery-Database-Id: 526fdbd8e4b07c3286b537f1"
-H "Content-Type: application/json"
-d '{"location": [16.373, 48.208], "name": "Vienna"}'
https://api.appery.io/rest/1/db/collections/cities/
File
File type can be used to store any sort of file. While clicking on the cell with the File type, the Media Manager opens. By clicking “Upload file,” you can choose any file with a non-empty body and size up to 20MB. You can also insert the same file in other rows.
To remove a file from a certain row, click on a cell where it is located and then choose “Reset” in Media Manager.
To remove files from the Media Manager, choose the needed file and click “Delete file.” This operation cannot be undone.
All uploaded files are added to the predefined Files collection. This also works conversely: if the file was added to the predefined Files collection, it will also be available in Media Manager.
Media Manager only contains files related to a database where they have been added.
File type object must contain originalFileName and fileName fields.
Security
Security
When you access the Appery.io database via the REST API key, access can be restricted by the ACL. The ACL is formatted as a JSON object where the keys are either object IDs or the special key ** to indicate public access permissions. The values of the ACL are permission objects: JSON objects whose keys are the permission name and a value that is always true.
For example, if you want the user with ID 5278cafce4b01085e4b7945a to have to read-and-write access to an object, as well as make the object publicly readable, the corresponding ACL is:
{
"54539efee4b05c4ac3b9737f": { "read": true, "write": true },
"*" : { "read" : true }
}
If you want to hide any record from a specific user, set the read property to false. Note that the * symbol has a priority, so you need to remove it from the ACL:
{
"54539efee4b05c4ac3b9737f":{"read":false,"write":true}
}
In the database editor, it looks like:
You can still read and modify ACLs via the REST API, just by accessing the ACL key of an object.
For instance, the following example updates the ACL data of one of the tasks. Log in to the database, as shown in signing in.
Set up the service as you would for an object update. You need to add the X-Appery-Session-Token, (which you get upon login), and the ACL field with the type of object:
curl -X PUT
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: c6771e2f-44ae-42ea-9946-5fa320578233"
-d "{"acl":{"*":{"read":true,"write":false},"5588396fe4b0b40eb7839d0a":{"read":true,"write":true}}}"
https://api.appery.io/rest/1/db/users/54539efee4b05c4ac3b9737f
Remember that if the user doesn’t have permission to write the object, it cannot be updated. So you have to change the write property from the database editor.
If you want to access your data and ignore all ACLs, you can use the X-Appery-Master-Key header instead of X-Appery-Session-Token provided in the database Settings tab:
For security, the master key should not be distributed to end users, but if you are running code in a trusted environment, feel free to use the master key for authentication.
Objects
Database objects.
Objects or records are created, retrieved from a database collection.
Format
Object format.
The Appery.io database stores data in JSON format (it’s running MongoDB). For example, if you are building a ToDo app, a task object might look like:
{
"priority": "High",
"taskName": "Use cool API"
}
When a new object is created, the following three columns are automatically created: _createdAt, _updatedAt, and _id. These field names are reserved, so you cannot set them yourself. Using the object above, if you did a GET on it, it would look like this, including the reserved fields:
{
"_id":"544fc7f1e4b0c9bce1295c78",
"taskName":"Use Cool API",
"_createdAt":"2014-10-28 16:44:33.374",
"_updatedAt":"2014-10-28 16:44:36.922",
"priority":"high"
}
If the collection name is todo, then the URL to the collection would be:
https://api.appery.io/rest/1/db/collections/todo
If you want to work with a particular object (for instance, the above example), then the URL would be either this:
https://api.appery.io/rest/1/db/collections/todo/[object_id]
Or this:
https://api.appery.io/rest/1/db/collections/todo/544fc7f1e4b0c9bce1295c78
To make it easy to work with collections and objects, you can get the almost-complete curl command for each REST verb. Click on any of the REST verbs (GET, FIND, CREATE, UPDATE, DELETE) to get the curl request.
Number of records
There is a default limit parameter which equals 100. That means that only 100 records will be returned if other wasn’t specified. To avoid this limitation, use the limit parameter in the requests and specify your own value. Max value is 1500.
For more precise examples, documentation below uses Students collection with following structure:
string
number
array
John
10
[10,9,3]
Donna
20
[2,8,1]
...
...
...
Dina
100
[10,8,9]
Retrieve a Specific Object
Retrieving a specific object
To retrieve a specific object, execute a GET command and also add the object ID to the end of the URL.
https://api.appery.io/rest/1/db/collections/<collectionName>/<objectId>
The following curl shows how to retrieve a specific object from the database:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
https://api.appery.io/rest/1/db/collections/todo/54578046e4b0c9bce12bd075
{
"_id":"5278caf4e4b01085e4b79456",
"_createdAt":"2013-11-05 10:39:48.757",
"_updatedAt":"2014-08-26 09:50:03.015",
"marks":[
4.0,
1.0,
10.0
],
"studentId":60.0,
"studentName":"John"
}
Deleting an Object
Deleting an object.
To delete an object, send a DELETE request with the object ID in the URL.
https://api.appery.io/rest/1/db/collections/<collectionName>/<objectId>
The result is an empty JSON object.
Create Object
Creating object.
Creating new objects is done with a POST request.
https://api.appery.io/rest/1/db/collections/<collectionName>
If the creating was successful you’ll get a status code 200 OK and response, containing auto-generated _id for the new object and _createdAt timestamp, which specifies, when the object was created.
curl -X POST
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "Content-Type: application/json"
-d "{'studentName':'Frank', 'studentId':110, 'marks':['1,5,6']}"
https://api.appery.io/rest/1/db/collections/students
{
"_id":"557edfcae4b0f840f33480ef",
"_createdAt":"2015-06-15 14:23:06.698"
}
Retrieve All Objects
Retrieving all objects.
To retrieve all the objects, use a GET request and specify the collection name.
https://api.appery.io/rest/1/db/collections/<collectionName>
The response body is a JSON object containing all the user-provided fields, plus the _createdAt, _updatedAt, and _id fields.
curl -X GET -H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
https://api.appery.io/rest/1/db/collections/students
[
{
"_id":"5278caf6e4b01085e4b79457",
"_createdAt":"2013-11-05 10:39:50.456",
"_updatedAt":"2014-08-26 09:50:03.015",
"marks":[
8.0,
8.0,
5.0
],
"studentId":10.0,
"studentName":"Donna"
},
//...all the objects
{
"_id":"5278cb0ae4b01085e4b7945f",
"_createdAt":"2013-11-05 10:40:10.400",
"_updatedAt":"2014-08-26 09:50:03.015",
"marks":[
7.0,
6.0,
5.0
],
"studentId":100.0,
"studentName":"Dina"
}
]
Update an Array Column
Update an array column.
To help with storing array data, there are three operations that can be used to automatically change an array field:
- Add – appends the given array of objects to the end of an array field.
- AddUnique – adds only the given objects that aren’t already contained in an array field. The position of the insert is not guaranteed.
- Remove – removes all instances of each given object from an array field.
Each method takes an array of objects to add or remove in the objects key. Use a PUT command to add an array of objects. Remember to paste the object ID in the end of the URL.
https://api.appery.io/rest/1/db/collections/<collectionName>/<objectId>
The result is JSON containing the object update time.
__op defines a kind of operation. It can be Add, AddUnique, and Remove, as in the example above.
When working with arrays, make sure you:
- Clean the localStorage variable value after you store the array to the database. Otherwise, you can get incorrect data, and errors will appear.
- Check the type of the array and database elements – they should be the same.
For example, when you store an array of objects to the database and you have this in a column:
["{name=xxxxxx, email=xxxxxx@xxxxxx}","{name=xxxxxx, email=xxxxxx@xxxxxx}"]
This means you stored an array of strings, not array of objects. You will get a TypeError message, because you have no objects in the array.
In this case, you should convert the strings to an array of objects. The following JavaScript code example can help:
function strRepresentationToObject(str) {
str = str.slice(1, -1);
var i, len, obj={}, tmp, arr = str.split(', ');
for (i = 0, len = arr.length; i < len; i++) {
tmp = arr[i].split('=');
obj[tmp[0]] = tmp[1];
}
return obj;
}
if (value == "") {
return "[]";
}
var i, len, newValue = [];
for (var i = 0, len = value.length; i < len; i++) {
newValue.push(strRepresentationToObject(value[i]));
}
return JSON.stringify(newValue);
curl -X PUT
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "Content-Type: application/json"
-d '{"marks":{"__op":"AddUnique","objects":[5, 2]}}'
https://api.appery.io/rest/1/db/collections/students/544fc7f1e4b0c9bce1295c78
{
"_updatedAt":"2015-06-15 15:05:53.061"
}
Update Multiple Objects
Updating multiple objects.
By using the an operations parameter, you can update multiple objects at once. As with single object updating, you should use the PUT method, (there is no need to specify the object ID).
Note
See the full list of supported operators, and read more about the operations parameters here.
https://api.appery.io/rest/1/db/collections/<collectionName>/
Example
By mixing the where and operations parameters, you can conditionally update multiple objects. Only objects that satisfy the where condition will be updated.
The query below finds all of the records where studentId equals 20 and changes it to 60.
Also, an update parameter is available when updating multiple objects. You can specify what fields the object should be updated in, and the values to change them.
Note
If the operations object is specified then the update parameter is fully ignored. Their functionality can not be used simultaneously.
Note
Read more about the where and operations parameters.
Updating arrays and pointers is also available for the update parameter. If we assume that your collection contains a column user with a pointer type to _users collection, you can update the marks column type of array.
The example will change all of the values in the studentId column to 60.
curl -X PUT
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "Content-Type: application/json"
-d 'operations={"$set":{"studentId":60}}'
https://api.appery.io/rest/1/db/collections/students/
curl -X PUT
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "Content-Type: application/json"
-d 'where={"studentId":20}'
-d 'operations={"$set":{"studentId":60}}'
https://api.appery.io/rest/1/db/collections/students/
Example
The following example finds all of the records where the studentId equals 20, and changes studentName field to 60:
curl -X PUT
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "Content-Type: application/json"
-d 'where={"studentId":20}'
-d 'update={"studentName":60}'
https://api.appery.io/rest/1/db/collections/students/
The example finds all the records where studentId equals 20, and changes the value in the user column to 5540ed6ae4b020ea2fabaf44. It also adds a new array values into marks array – 5 and 2.
curl -X PUT
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "Content-Type: application/json"
-d 'where={"studentId":20}'
-d 'update={"user": {"collName":"_users", "_id":"5540ed6ae4b020ea2fabaf44"}, "marks":{"__op":"AddUnique","objects":[5, 2]}}'
https://api.appery.io/rest/1/db/collections/students/
Update an Object
Updating objects
To update or change an object, send a PUT request. Since you are changing a particular object, the object ID needs to be used in the URL.
https://api.appery.io/rest/1/db/collections/<collectionName>/<objectId>
The result is a JSON containing the object update time.
Batch Operations
Perform several operations in a single API call.
A batch operation performs several API calls in a single call.
Batch API Calls Count
When performing a batch operation, the actual number of API calls is the number of calls inside the batch operation. For example, if a batch operation updates 5 objects, it will count as 5 platform API calls.
To execute a batch operation send the following request:
curl -X POST \
-H "Content-Type: application/json" \
-H "X-Appery-Database-Id: <database_id>" \
[-H "X-Appery-Session-Token: <session_token>" \]
-d "<operations_array>" \
https://api.appery.io/rest/1/db/batch
operations_array is a JSON array of objects containing batch operations description. For example:
[
{
"method": "<method>",
"collection": "<collection_name>",
"_id": "<object_id>",
"data": <object_data>
},
{
"method": "<method>",
"collection": "<collection_name>",
"_id": "<object_id>",
"data": <object_data>
},
]
method
GET, POST, PUT or DELETE.
Yes.
collection_name
Database collection name.
Yes
object_id
Object ID to perform the operation on.
Required for GET, PUT or DELETE.
object_data
Object data for the operation.
Required for POST or PUT.
The database returns HTTP 200 OK status and JSON array representing results for the operations requested.
If an operation fails on a specific objects, operations on other objects will continue.
The position of the operation result item is the same as the position of the operation description in the request. For example:
[
{
"<operation_status>": <operation_result>
},
{
"<operation_status>": <operation_result>
},
]
operation_status
success or error.
operation_result
JSON object representing operation response which is usually returned by a direct service invocation (see Collections REST API for more details), including error responses.
For collection Labels with one custom column name (string):
Batch operation has the following format:
curl -X POST \
-H "Content-Type: application/json" \
-H "X-Appery-Database-Id: 58a59358975a4fa00e0ff50f" \
https://api.appery.io/rest/1/db/batch
-d
"[
{
"method": "post",
"collection": "Labels",
"data": {"name": "nick"}
},
{
"method": "put",
"collection": "Labels",
"_id": "58a59386975a4fa00e0ff513",
"data": {"name": "max updated"}
},
{
"method": "delete",
"collection": "Labels",
"_id": "58a59381975a4fa00e0ff512"
},
{
"method": "get",
"collection": "Labels",
"_id": "58a59386975a4fa00e0ff513"
},
{
"method": "put",
"collection": "Labels",
"_id": "000000000000000000000000",
"data": {"name": "unexisting label with _id 000000000000000000000000"}
}
]"
[
{
"success": {
"_id": "58a5962d0a975a799b278abd",
"_createdAt": "2017-02-16 12:08:13.327"
}
},
{
"success": {
"_updatedAt": "2017-02-16 12:08:13.337"
}
},
{
"success": {}
},
{
"success": {
"_id": "58a59386975a4fa00e0ff513",
"name": "max updated",
"_createdAt": "2017-02-16 11:56:54.725",
"_updatedAt": "2017-02-16 12:08:13.337"
}
},
{
"error": {
"code": "DBSU205",
"description": "Collection 'Labels' doesn't contain object with id 000000000000000000000000."
}
}
]
where Clause
Query constraints
It’s possible to specify a where clause in the request. The value of the where parameter needs to be in JSON format. As you’re sending a GET request, the JSON value is also then URL encoded.
Example below will return records where studentId=50.
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": 50}'
https://api.appery.io/rest/1/db/collections/todo
[
{
"_id":"5278cb01e4b01085e4b7945d",
"_createdAt":"2013-11-05 10:40:01.184",
"_updatedAt":"2015-06-18 12:06:10.177",
"marks":[
7.0,
6.0,
5.0
],
"studentId":50.0,
"studentName":"Dan"
}
]
The where parameter also supports the following comparison values:
- $lt – less than.
- $lte – less than or equal to.
- $gt – greater than.
- $gte – greater than or equal to.
- $ne – not equal to.
- $in – contained in.
- $nin – not contained in.
- $exists – a value is set for the key.
- $not – not match the expression.
Less than ($lt)
If you want to get only the students where the studentId is less than 50 ($lt):
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$lt": 50}}'
https://api.appery.io/1/db/collections/students
The result is only the students with student ID of 10, 20, 30, and 40.
Less than or equal to ($lte)
If you want to get only students where the studentId is less than or equal to 50 ($lte):
curl -X GET
-H "X-Appery-Database-Id: 526fdbd8e4b07c3286b537f1"
-d 'where={"studentId": {"$lte": 50}}'
https://api.appery.io/1/db/collections/students
The result is the same as the previous example, except now it also includes 50.
Greater than ($gt)
Going the opposite way, if you want to show all students with a studentId of greater than 50 ($gt):
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$gt": 50}}'
https://api.appery.io/1/db/collections/student
This would return objects with IDs of 60, 70, 80, 90, and 100.
Greater than or equal to ($gte)
Using greater than or equal to ($gte) is very similar:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$gte": 50}}'
https://api.appery.io/1/db/collections/students
Not equal to ($ne)
By using not equal to ($ne), you can specify which object you don’t want to select:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$ne": 20}}'
https://api.appery.io/1/db/collections/students
You will get all the student objects except the student with the ID of 20.
Contained in ($in)
To get specific objects, use contained in ($in):
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$in": [20,80]}}'
https://api.appery.io/1/db/collections/students
This will return only student objects with IDs of 20 and 80
Not contained in ($nin)
The opposite of contained in ($in) is not contained in ($nin):
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$nin": [20,80]}}'
https://api.appery.io/1/db/collections/students
This would return all objects besides objects with IDs of 20 and 80.
A value is set ($exists)
$exists option checks whether a value is set for a column:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$exists":true}}'
https://api.appery.io/1/db/collections/students
As every object has the ID set, the above query would return the entire list. Or, specifying false. It would return an empty list, as every object has the student ID set.
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentId": {"$exists":false}}'
https://api.appery.io/1/db/collections/students
Not match the expression ($not)
$not performs a logical NOT operation on the specified operator expression and selects the documents that do not match the operator expression.
This request will return all records where studentId is NOT greater than 30.
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "studentId": { "$not": { "$gt":30 } } }'
https://api.appery.io/1/db/collections/students
On String Value
Queries on string values
You can use regular expressions to search over values containing strings. The constraint is represented by a hash with the key $regex mapping to a regular expression.
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"studentName": {"$regex": "^A"}}'
https://api.appery.io/1/db/collections/students
Multiple where Clauses
Multiple where clauses.
The Appery.io database also supports multiple where clauses. Read more about this on the MongoDB documentation page.
Multiple where examples.
Logical OR ($or)
The $or operator performs a logical OR operation on an array of two or more expressions, and selects the documents that satisfy at least one of the expressions.
curl -X GET
-H "X-Appery-Database-Id:544a5cdfe4b03d005b6233b9"
-d 'where={"$or": [{"studentId": 50},{"studentName": "Dan"}]}'
https://api.appery.io/1/db/collections/students
Example above means that the returned object must contain {"studentId":50} OR {"studentName":"Dan"}.
Logical AND ($and)
$and performs a logical AND operation on an array of two or more expressions and selects the documents that satisfy all the expressions in the array. The $and operator uses short-circuit evaluation: If the first expression evaluates to false, remaining expressions will not be evaluated:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"$and": [{"priority": "Low"},{"taskName": "Create an app"}]}'
https://api.appery.io/1/db/collections/todo
Example above means that the returned object must contain {"studentId":50} AND {"studentName":"Dan"}.
Logical NOR ($nor)
$nor performs a logical NOR operation on an array of one or more query expressions and selects the documents that fail all the query expressions in the array:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"$nor": [ { "studentName": "John" }, { "studentId": 50 } ] }'
https://api.appery.io/1/db/collections/students
Example above means that the returned object must NOT contain {"studentName":"John"} AND {"studentId": 50}.
On Date Value
Date queries
All of the comparison operators can be used to work with the value type of date.
Examples in this section are based on data in the following sample collection:
string
date
string
Debug soft
2014-11-12 19:00:00.000
High
Use cool API
2014-11-10 20:00:00.000
Low
Create an app
2014-11-09 09:00:00.000
High
Retrieve all the objects that equal the specific date value:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "time":"2014-11-12 19:00:00.000"}'
https://api.appery.io/1/db/collections/todo
To get all the objects that contain a date greater than a certain value, use the $gt operator. This will retrieve all objects that contain dates greater (later) than the 10th of November 2014:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "time" : {"$gt" :"2014-11-10 00:00:00.000"} }'
https://api.appery.io/1/db/collections/todo
To get all the objects with dates less than a certain value, use the $lt operator. This will retrieve all objects with dates less than (earlier) the 10th of November 2014:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "time" : {"$lt" :"2014-11-10 00:00:00.000"} }'
https://api.appery.io/1/db/collections/todo
It’s also possible to retrieve dates in a certain range. Use a combination of the $lt and $gt operators. This will retrieve all objects with dates between the 9th and 11th of November 2014:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "time" : {"$gt":"2014-11-09 00:00:00.000" , "$lt" :"2014-11-11 00:00:00.000"} }'
https://api.appery.io/1/db/collections/todo
Accessing _createdAt and _updatedAt columns
You need to use a different syntax to access the predefined columns _createdAt and _updatedAt via a REST service. The date value must be presented like the following:
{ "time" : "2014-11-04T15:25:19.437Z" }
Also, the where clause must contain the $date variable and look like the following:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"_createdAt":{"$date":"2014-11-04T15:25:19.437Z"}}'
https://api.appery.io/1/db/collections/todo
The _updatedAt column can be accessed the same way:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"_updatedAt":{"$date":"2014-11-07T15:48:20.518Z"}}'
https://api.appery.io/1/db/collections/todo
Counting Objects
Counting objects.
It is possible to send a request to return the number of objects in a collection.
To count the number of objects in a collection:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'count=1'
https://api.appery.io/rest/1/db/collections/todo
Sorting
Sorting.
To sort data, specify sort as a request parameter. Also, specify the column by which you want to sort.
For example, sort by the studentName column, in ascending order:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'sort=studentName'
https://api.appery.io/1/db/collections/students
To sort in descending order, specify the column name with - before it:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'sort=-studentName'
https://api.appery.io/1/db/collections/students
You can also sort by more than one column:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'sort=studentName,studentId'
https://api.appery.io/1/db/collections/students
On Pointer Value
Queries on pointer values.
You can run queries on pointer values.
To properly get an object with a specific pointer value, you should provide an object with exactly the same fields in the where parameter:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"subtask": {"collName":"todo", "_id":"5458efdfe4b0c9bce12bd58a"}}'
https://api.appery.io/rest/1/db/collections/todo/
Parameters Order
For this query to work properly, it's import to keep the parameter order as shown in the example. For example { "_id":"57b6bd3be4b07e8542fd8ae8", "collName":"Categories"} will not work.
An alternative way to setup the query is like this:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={"subtask._id":"5458efdfe4b0c9bce12bd58a"}'
https://api.appery.io/rest/1/db/collections/todo/
On Array Value
Queries on array values.
You can run queries on array value.
Retrieve all objects with an array that contains the number 1:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "marks": 1}'
https://api.appery.io/rest/1/db/collections/students
Note
There are several special operators that MongoDB provides for array queries.
The $all operator can be used to select the documents where the value of a field is an array that contains all the specified elements.
Retrieve all objects that contain array with 5, 6 and 7:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "marks": { "$all": [5, 7, 6 ] }}'
https://api.appery.io/rest/1/db/collections/students
It’s possible to retrieve elements by array size, using the $size operator.
Retrieve all the objects that contain an array with 3 elements:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "marks": { "$size": 3 }}'
https://api.appery.io/rest/1/db/collections/students
It’s also possible to use the $elemMatch operator to match more than one component within an array element. In this case, the array structure must be a little more complex.
The marks column with array of objects:
string
number
array
John
10
[{“math”:”5″, “physics”:”7″}]
By using the $elemMatch operator, it’s possible to make a query for each of object fields. Therefore, it’s possible to retrieve all object arrays where the mark for math equals 5, and mark for physics is greater than 6:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={ "marks": { "$elemMatch": { "math": "5", "physics" : { "$gt" : "6"}}}}'
https://api.appery.io/rest/1/db/collections/students
On Geospatial Value
Geospatial queries
You can run queries on Geospatial data. Examples in this section will use the following sample data:
string
Geopoint
Munich
[11.574, 48.143]
Athens
[23.729, 37.985]
Amsterdam
[4.895, 52.373]
Vienna
[16.375, 48.208]
You can use different queries to work with your geopoints data. This can be handy when you’re developing an app with GPS services. The query itself must be placed in the where parameter:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={/* some query */}'
https://api.appery.io/rest/1/db/collections/cities/
80 miles diameter around Vienna:
{
"location" : {
"$nearSphere" : [16.373, 48.208],
"$maxDistanceInMiles" : 80
}
}
[
{
"location":[
48.208,
16.373
],
"name":"Vienna"
}
]
550 kilometers diameter around Vienna:
{
"location" : {
"$nearSphere" : [16.373, 48.208],
"$maxDistanceInKilometers" : 550
}
}
[
{
"location":[
48.208,
16.373
],
"name":"Vienna"
},
{
"location":[
48.143,
11.574
],
"name":"Munich"
}
]
(0.21 radians [1350 km] diameter around Vienna:
{
"location" : {
"$nearSphere" : [16.373, 48.208],
"$maxDistanceInRadians" : 0.211897661
}
}
[
{
"location":[
48.208,
16.373
],
"name":"Vienna"
},
{
"location":[
48.143,
11.574
],
"name":"Munich"
},
{
"location":[
37.985,
23.729
],
"name":"Athens"
}
]
Nearest to Vienna without distance limit:
{
"location" : {
"$nearSphere" : [16.373, 48.208]
}
}
[
{
"location":[
48.208,
16.373
],
"name":"Vienna"
},
{
"location":[
48.143,
11.574
],
"name":"Munich"
},
{
"location":[
37.985,
23.729
],
"name":"Athens"
},
{
"location":[
52.373,
4.895
],
"name":"Amsterdam"
}
]
Cities within a box [by SW and NE corners], [11,48] – SW, [20,50] – NE):
{
"location" : {
"$within" : {
"$box" : [[11, 48],[20, 50]]
}
}
}
[
{
"location":[
48.208,
16.373
],
"name":"Vienna"
},
{
"location":[
48.143,
11.574
],
"name":"Munich"
}
]
Cities within a circle, with the center in Bratislava and a diameter of 100 kms:
Distinct Values
Distinct values
It’s possible to retrieve all distinct values of a collection’s column using a POST request.
curl -X POST
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'where={/* criteria */}'
https://api.appery.io/rest/1/db/collections/[collectionName]/distinct/[columnName]
It’s also possible to use a GET request to retrieve distinct values:
curl -X GET
-H "Content-Type: application/json"
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
https://api.appery.io/rest/1/db/collections/<collection_name>/distinct/<column_name>?where=
Limit
Pagination.
To limit the number of objects you get, use the limit parameter. The following query will return the first 5 objects:
Note
Max value for limit parameter is 1500. The value is Integer (Number JavaScript).
curl -X GET
-H "X-Appery-Database-Id: 526fdbd8e4b07c3286b537f1"
-d 'limit=5'
https://api.appery.io/1/db/collections/students
In addition to specifying how many objects to return, you can also specify from which object count to start with the skip parameter. The following example will start at object 6 (skip the first 5) and return (limit) 5 objects.
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'limit=5'
-d 'skip=5'
https://api.appery.io/1/db/collections/students
Projection
Projection
You can use a Projection to return only specified collection columns. You can do this by adding a proj parameter to your request.
Note
Read more about MongoDB projection.
Here is how to retrieve only the studentName column:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'proj={"studentName":1}'
https://api.appery.io/rest/1/db/collections/students
When the certain column is marked with number 1 – MongoDB assumes that all other columns shouldn’t be retrieved. To retrieve several columns, specify them, separated by commas:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'proj={"studentName":1,"studentId":1}'
https://api.appery.io/rest/1/db/collections/students
You can also specify which column should be excluded from the result. In this case, all columns will be retrieved except the excluded ones. To do this, mark column name with zero:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'proj={"studentName":0}'
https://api.appery.io/rest/1/db/collections/students
You cannot mix including and excluding fields due to MongoDB limitation.
You can mix the include parameter with proj to specify what columns should be retrieved from related object.
The following example retrieves only studentName and studentId fields from the collection in which the request was made, and only email from the related object:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-d 'include=owner'
-d 'proj={"studentName": 1, "studentId":1, "owner": {"email": 1}}'
https://api.appery.io/rest/1/db/collections/students
Files
The file API allows you to upload and download files.
All file APIs require sending an X-Appery-Session-Token header. You can get its value when a user signs in. This is to prevent anyone but the user from uploading files.
Retrieving File List
Retrieving files list
To retrieve a files list based on the files in the Files collection, send GET request and specify database id:
https://api.appery.io/rest/1/db/files
It’s necessary to provide an X-Appery-Session-Token or X-Appery-Master-Key to get the file list. In the case of using the X-Appery-Session-Token file, the list will contain only those files that where uploaded by the current user, or files that were uploaded via the Media Manager, and doesn’t contain default ACL:
If the ACL for the file defines that a certain user doesn’t have read rights, the file will be excluded from the files list:
Now user Pete will not get this file in the list:
curl -X GET
-H "Content-Type: text/xml"
-H "X-Appery-Database-Id: 526fdbd8e4b07c3286b537f1"
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e"
https://api.appery.io/rest/1/db/files/31bb3831-a18e-4a3a-b720-0747a0901481.config.xml
{
"status":403,
"uri":"https://api.appery.io/rest/1/db/files/526fdbd8e4b07c3286b537f1/31bb3831-a18e-4a3a-b720-0747a0901481.config.xml",
"response":{
"code":"DBFG333",
"description":"Access denied: you don't have read permission on specified object"
}
}
By using the X-Appery-Master-Key, all the files from the Files collection will be included into the file list, despite specified ACL.
Use encoded parameter with base64 value to return the result as base64:
curl -X GET
-H "Content-Type: text/xml"
-H "X-Appery-Database-Id: 526fdbd8e4b07c3286b537f1"
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e"
https://api.appery.io/rest/1/db/files/31bb3831-a18e-4a3a-b720-0747a0901481.config.xml?encoded=base64
{
"base64data" : <base64data>
}
File content will be presented as field of base64data parameter.
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e"
https://api.appery.io/rest/1/db/files/544a5cdfe4b03d005b6233b9
[
{
"_id":"7cdec132-5d98-403e-ab37-9ea1cca96299.database_source.txt",
"contentType":"text/plain",
"owner":null,
"_createdAt":"2015-06-22 16:08:31.110",
"length":169551,
"acl":null
},
{
"_id":"31bb3831-a18e-4a3a-b720-0747a0901481.config.xml",
"contentType":"text/xml",
"owner":null,
"_createdAt":"2014-07-21 12:09:49.488",
"length":26,
"acl":null
},
{
"_id":"3f612c86-2beb-4064-bdbe-14a3d2bf0457.cta.kml",
"contentType":"application/octet-stream",
"owner":null,
"_createdAt":"2014-07-21 11:59:50.108",
"length":47667,
"acl":null
}
]
Retrieving a File
Retrieving file
To retrieve any file you need, add the name to the end of the URL, and use a GET request:
https://api.appery.io/rest/1/db/files/<fileName>
cURL:
curl -X GET
-H "Content-Type: application/octet-stream"
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e"
https://api.appery.io/rest/1/db/files/3f612c86-2beb-4064-bdbe-14a3d2bf0457.cta.kml
Deleting a File
Deleting files
Deleting files is similar to retrieving them; the only difference is the command type. Use a DELETE request:
https://api.appery.io/rest/1/db/files/<fileName>
cURL:
curl -X DELETE
-H "Content-Type: application/octet-stream"
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e"
https://api.appery.io/rest/1/db/files/3f612c86-2beb-4064-bdbe-14a3d2bf0457.cta.kml
There is no response for this operation.
Direct Link to a File
Direct link to a file
The file can be downloaded with the direct link. To do it, use a URL with the following format:
https://api.appery.io/rest/1/db/files/<databaseID>/<fileName>?encoded=<encoded>&sessionToken=<userSessionToken>&masterKey=<masterKey>
databaseID
Is the id of the database where the file is stored.
fileName
The name added to the file upon uploading to the Appery.io database.
encoded
If value of encoded parameter = base64, file content will be returned as base64 string.
userSessionToken (optional)
Can be used to restrict users access.
masterKey (optional)
Can be used to ignore ACLs (full access to data).
The resulting link looks like the following:
curl -X GET
https://api.appery.io/rest/1/db/files/544a5cdfe4b03d005b6233b9/31bb3831-a18e-4a3a-b720-0747a0901481.config.xml?sessionToken=26960cec-216e-4fd2-9095-270b02686a6f
Uploading Multipart Data
Uploading multipart data
To upload multiple files with form data, send POST request to the following URL:
https://api.appery.io/rest/1/db/files/
cURL:
curl -X POST \
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9" \
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e" \
-H "Content-Type: multipart/form-data" \
-F <fileName1>=@<filePath1> \
-F <fileName2>=@<filePath2> \
-F <fileName3>=@<filePath3> \
https://api.appery.io/rest/1/db/files/
,
{"success":
{
"filename":"c2c638c1-2add-40da-bbd1-e1ff662093ce.secondFile.txt",
"fileurl":"https://api.appery.io/rest/1/db/files/534fc8eee4b0790ac5d968fe/c2c638c1-2add-40da-bbd1-e1ff662093ce.secondFile.txt"
}},
{"error":
{
"code":"DBFM153",
"description":"File contents should be provided"
}}
]
[
{"success":
{
"filename":"c2c638c1-2add-40da-bbd1-e1ff662093ce.firstFile.txt",
"fileurl":"https://api.appery.io/rest/1/db/files/534fc8eee4b0790ac5d968fe/c2c638c1-2add-40da-bbd1-e1ff662093ce.firstFile.txt"
}},
{"success":
{
"filename":"c2c638c1-2add-40da-bbd1-e1ff662093ce.secondFile.txt",
"fileurl":"https://api.appery.io/rest/1/db/files/534fc8eee4b0790ac5d968fe/c2c638c1-2add-40da-bbd1-e1ff662093ce.secondFile.txt"
}},
{"error":
{
"code":"DBFM153",
"description":"File contents should be provided"
}}
]
Uploading a File
Uploading files
There are number of ways to upload files to a database:
- Files can be uploaded to the database directly from the database dashboard using the Media Manager.
- Files can be uploaded from the app you are creating:
- jQuery Mobile apps:
- Using a ready-to-use plug-in: Upload File to Database.
- A step-by-step tutorial that uses JavaScript code.
- AngularJS apps:
- Using a ready-to-use plug-in: Files Upload.
- jQuery Mobile apps:
To upload a file, send POST request to the following URL:
https://api.appery.io/rest/1/db/files/<fileName>
Use --form parameter and multipart/form-data for Content-Type to upload with FormData:
curl -X POST \
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9" \
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e" \
-H "Content-Type: multipart/form-data" \
--form file=@<filePath> \
https://api.appery.io/rest/1/db/files/myFile.txt
cURL:
curl -X POST \
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9" \
-H "X-Appery-Session-Token: 6fb9515d-82fd-43b3-9124-f0534dceca8e" \
-H "Content-Type: <contentType>" \
-d "<fileContent>" \
https://api.appery.io/rest/1/db/files/myFile.txt
{
"filename":"c2c638c1-2add-40da-bbd1-e1ff662093ce.myFile.txt",
"fileurl":"https://api.appery.io/rest/1/db/files/534fc8eee4b0790ac5d968fe/c2c638c1-2add-40da-bbd1-e1ff662093ce.myFile.txt"
}
User
Many mobile apps have the notion of a user -- where each user may sign up for an account in the app, view his or her information, perform actions, and change his or her password. As this functionality is very common, the Appery.io Database comes with a built-in User Management feature. Users are created in the built-in collection called Users, and are managed via the predefined Users collection.
A user object is very similar to any other object you create, with one exception; the user object requires username and password fields. The password field is stored encrypted in the database, and will not be shown in any client request.
User Queries
User queries.
Queries with the Users collection can be performed in the same way as any other collection. All of the query constraints can be used.
This examples hows how to get all users with username Dan:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: X-Appery-Session-Token"
-G --data-urlencode 'where={"username":"Dan"}'
https://api.appery.io/rest/1/db/users
This example shows how to retrieve all users with email domain @mail.com domain:
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: X-Appery-Session-Token"
-G --data-urlencode 'where={"email": {"$regex": "@mail.com"}}'
https://api.appery.io/rest/1/db/users
Sign In (Login)
/db/login
A user login will login a user into the backend (database) and return a session token. A session token is then passed with other APIs to do actions on behalf of this user.
username
Yes
User username.
password
Yes.
User password.
The sessionToken should be saved to access the user information in subsequent requests. You can save the token in browser's local storage.
Only the sessionToken and _id parameters will be returned in the response after successful authentication. If you want to retrieve custom fields (as email) that were created in Users collection you should send second request after authentication.
To change the sessionToken lifetime, go to Database > Settings and specify session timeout you need.
curl -X GET \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-G --data-urlencode 'username=amy' \
--data-urlencode 'password=123' \
https://api.appery.io/rest/1/db/login
{
"_id": "5792b0c9e4b00ef864f3dc59",
"sessionToken": "1f54265f-ef5b-4b96-8163-01e4840a3915"
}
Signup (Registration)
/db/users
New user sign up will create a new user in the User collection.
username
Yes
New user username.
password
Yes
New user password.
columnName
No
Additional columns present in Users collection.
In addition to the required parameters you can add custom columns and fill them out during user registration.
To reduce the number of errors, the Appery.io database doesn’t allow the creation of new fields from a POST request. First, the fields need to be added in the web console. Once it’s done, you can add a new user with the new field.
New user registration with just the username and password.
curl -X POST \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-H "Content-Type: application/json" \
-d "{'username':'alexa','password':'456'}" \
https://api.appery.io/rest/1/db/users
{
"_id": "5792b95fe4b079a3621798b8",
"username": "alexa",
"_createdAt": "2016-07-23 00:25:03.361",
"_updatedAt": "2016-07-23 00:25:03.364",
"acl": {
"*": {
"read": true
},
"5792b95fe4b079a3621798b8": {
"read": true,
"write": true
}
},
"sessionToken": "68bbb336-cec1-416e-976b-5452dfa9be52"
}
This examples shows how to send additional column information during registration. Note that the column has to exist in the database collection.
curl -X POST \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-H "Content-Type: application/json" \
-d "{'username':'alexa','password':'456', 'email':'alexa@appery.io'}" \
https://api.appery.io/rest/1/db/users
{
"_id": "5792ba75e4b079a3621798db",
"username": "alexa",
"_createdAt": "2016-07-23 00:29:41.650",
"_updatedAt": "2016-07-23 00:29:41.653",
"acl": {
"*": {
"read": true
},
"5792ba75e4b079a3621798db": {
"read": true,
"write": true
}
},
"sessionToken": "606a5b2c-5e3c-48a8-931f-49db227dbd24"
}
Retrieve User Details
/db/users/{userID}
Retrieves information about a user specified by its user ID. Works the same way as Retrieve Current User endpoint by requires the user ID. With this endpoint you can get information about the currently signed in user unless you specify the Master key. With the Master key you can get information about any user in the Users collection.
This example shows getting information about the currently signed in user:
curl -X GET \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-H "X-Appery-Session-Token: 6996c750-1c44-418e-8d6a-76ebdec2f7cb" \
https://api.appery.io/rest/1/db/users/5797dfd5e4b0264ccd2efde6
{
"_id": "5797dfd5e4b0264ccd2efde6",
"username": "amy",
"_createdAt": "2016-07-26 22:10:29.264",
"_updatedAt": "2016-08-03 23:53:51.272",
"acl": {
"*": {
"read": true
},
"5797dfd5e4b0264ccd2efde6": {
"read": true,
"write": true
}
},
"toProfile": {
"collName": "UserProfile",
"_id": "5797dfd5e4b0264ccd2efde8"
},
"Notes": "Nice user."
}
This example uses the Master key and allows to get details about any user in the User collection:
curl -X GET \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-H "X-Appery-Master-Key: 7ec7f59e-475d-49ba-a2d1-fc22df51eb55" \
https://api.appery.io/rest/1/db/users/5797dfd5e4b0264ccd2efde6
{
"_id": "5797dfd5e4b0264ccd2efde6",
"username": "amy",
"_createdAt": "2016-07-26 22:10:29.264",
"_updatedAt": "2016-08-03 23:53:51.272",
"acl": {
"*": {
"read": true
},
"5797dfd5e4b0264ccd2efde6": {
"read": true,
"write": true
}
},
"toProfile": {
"collName": "UserProfile",
"_id": "5797dfd5e4b0264ccd2efde8"
},
"Notes": "Nice user."
}
Deleting a User
Deleting a user.
To delete a user from the server, send a DELETE request and provide the X-Appery-Session-Token header to authenticate.
https://api.appery.io/rest/1/db/users/<users_id>
curl -X DELETE
-H "X-Appery-Database-Id: 526fdbd8e4b07c3286b537f1"
-H "X-Appery-Session-Token: dc99a77b-ad80-4055-b986-6157b192aa69"
https://api.appery.io/rest/1/db/users/54538e44e4b05c4ac3b9725d
Updating a User
Updating a user.
To update an existing user, send a PUT request specifying the fields you want to update. Any fields not included in the request will not be updated.
https://api.appery.io/rest/1/db/users/<users_id>
You need to specify the X-Appery-Session-Token for authentication, as well as the user ID in the URL.
curl -X PUT
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: c6771e2f-44ae-42ea-9946-5fa320578233"
-d "{"email":"stacy@somemail.com"}"
https://api.appery.io/rest/1/db/users/54539efee4b05c4ac3b9737f
Retrieving All Users
Retrieving all users.
You can retrieve multiple users at once by sending a GET request to the root user’s URL:
https://api.appery.io/rest/1/db/users
The returned JSON will include a list of all the users. You may also apply any of the queries options.
curl -X GET
-H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
-H "X-Appery-Session-Token: c6771e2f-44ae-42ea-9946-5fa320578233"
https://api.appery.io/rest/1/db/users
[
{
"_id":"54de4083e4b0cc014946181a",
"username":"Bob",
"_createdAt":"2015-02-13 18:20:51.591",
"_updatedAt":"2015-02-13 18:20:51.593",
"acl":{
"*":{
"read":true
},
"54de4083e4b0cc014946181a":{
"read":true,
"write":true
}
}
},
//...
{
"_id":"55883a0be4b0b40eb7839d18",
"username":"John",
"email":"john@mail.com",
"_createdAt":"2015-06-22 16:38:35.305",
"_updatedAt":"2015-06-22 16:38:35.307",
"acl":{
"*":{
"read":true
},
"55883a0be4b0b40eb7839d18":{
"read":true,
"write":true
}
}
}
]
Sign Out
db/logout
The sign out process will invalidate the user session on the server. This request requires sending the session token which will be invalidated. There is no response for this request in case of success.
curl -X GET \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-H "X-Appery-Session-Token: b3e7ab8e-39cb-40f8-a3fb-c0422f0c9aba" \
https://api.appery.io/rest/1/db/logout
Retrieve Current User
/db/users/me
include
No
Indicates which referenced objects and its data should be included in response.
projection
No
JSON projection object that was built in accordance with the documentation of MongoDB query.
curl -X GET \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-H "X-Appery-Session-Token: f1bb537e-e6ef-4d78-af67-3c4aa7e222db" \
https://api.appery.io/rest/1/db/users/me
{
"_id": "5797dfd5e4b0264ccd2efde6",
"username": "amy",
"_createdAt": "2016-07-26 22:10:29.264",
"_updatedAt": "2016-08-03 23:53:51.272",
"acl": {
"*": {
"read": true
},
"5797dfd5e4b0264ccd2efde6": {
"read": true,
"write": true
}
},
"toProfile": {
"collName": "UserProfile",
"_id": "5797dfd5e4b0264ccd2efde8"
},
"Notes": "Nice user."
}
You can also specify the include parameter to get referenced objects and their data from Pointer data type:
curl -X GET \
-H "X-Appery-Database-Id: 57928860e4b00ef864f3dc24" \
-H "X-Appery-Session-Token: f1bb537e-e6ef-4d78-af67-3c4aa7e222db" \
https://api.appery.io/rest/1/db/users/me?include=toPointer
{
"_id": "5797dfd5e4b0264ccd2efde6",
"username": "amy",
"_createdAt": "2016-07-26 22:10:29.264",
"_updatedAt": "2016-08-03 23:53:51.272",
"acl": {
"*": {
"read": true
},
"5797dfd5e4b0264ccd2efde6": {
"read": true,
"write": true
}
},
"toProfile": {
"_id": "5797dfd5e4b0264ccd2efde8",
"email": "amy@appery.io",
"country": "USA",
"acl": {
"5797dfd5e4b0264ccd2efde6": {
"read": true,
"write": true
}
},
"_createdAt": "2016-07-26 22:10:29.271",
"_updatedAt": "2016-07-26 22:10:29.271"
},
"Notes": "Nice user."
}
Overview
jQuery Mobile app JavaScript API.
Appery.io comes with a small JavaScript library to make it easier to select elements in the DOM in a jQuery Mobile app. The library provides a few functions on top of jQuery API to help you select elements and navigate int he app. For any other functions you should use the jQuery API.
jQuery API
It is important that you know how to select elements in the DOM using just the jQuery API.
Model
Apperyio.getModel(modelName, default).
Apperyio.getModel(modelName, default)
Creates a model object by its name or returns TypeNotFoundError if model type not found.
modelName
Model name described in Project > Model and Storage > Model view.
Yes.
default
Data to be used when an object is created.
No.
Product (Object)
name (String)
partNumber (Integer)
The following code will create an empty Product object:
var p = Apperyio.getModel("Product");
console.log(p);
{partNumber: 0, name: ""}
The following code will create a model object with default data:
Storage
Storage API.
get
Apperyio.storage.variableName.get()
{"partNumber": 1000, "name": "Smartphone"}
The following will return the entire expression stored in the variable (click on Result tab):
Apperyio.storage.Product.get();
{"partNumber": 1000, "name": "Smartphone"}
The following will return the specified field. This examples uses a Mapping Expression.
Apperyio.storage.Product.get("$['name']");
Smartphone
If you have a more complex structure such as shown below:
{"ProductList":[{"partNumber": 1000, "name": "Smartphone"},{"partNumber": 2000, "name": "Tablet"}]}
You can run a query that looks like this:
Apperyio.storage.ProductList.get("$['products'][1]");
{partNumber: 2000, name: "Tablet"}
You can also get a specific field from a selected object:
Apperyio.storage.ProductList.get("$['products'][1]['partNumber']");
2000
Use the following code to obtain a model name from a storage variable:
var type = Apperyio.storage.storageVariable.type;
update
Apperyio.storage.variableName.update(path, value)
{"partNumber": 1000, "name": "Smartphone"}
The following code will update the name field:
Apperyio.storage.Product.update("$['name']", "Smart Watch");
var p = Apperyio.storage.Product.get();
console.log(p);
{name: "Smart Watch", partNumber: 1000}
Here is another example but this time using a variable:
var fieldName = "name";
Apperyio.storage.Product.update("$['"+fieldName+"']", "Smart Watch");
var p = Apperyio.storage.Product.get();
console.log(p);
{name: "Smart Watch", partNumber: 1000}
Find a Component
Apperyio(id)
Apperyio ('component_name') is a shortcut to get a reference to a jQuery Mobile component on a screen by using its designated name. component_name is the name you set in Name property (in Properties panel).
jQuery API
It’s important to familiarize yourself with the jQuery and jQuery Mobile API.
Once you get a reference to an element, you can use the jQuery API to manipulate the element. It is a plain JavaScript and jQuery.
Here is example reading the input field value when clicking a button:
- Add a Click event to the button.
- Add a Run Custom Java Script action to the Click event.
- Add this JavaScript as the custom JavaScript (assuming the Input component name is Input).
var input = Apperyio('input');
alert (input.val());
Example
The example above is a quick and easy way to get access to any component in the screen. It’s equivalent to using jQuery directly:
var input = $('input[dsid="input"]');
alert (input.val());
Once you get a reference to a component, which part of the jQuery API is available depends on the component. For example, if you get a reference to an Input component, then you could use this to read or set its value:
Apperyio('input').val();
Apperyio('input').val('hello');
Example
If you get a reference to a Label component, then the API is different, and to read the value, you would use:
Apperyio('output').text();
Upload Binary Helper
uploadBinaryHelper(datasource, imageBase64, name, type)
The uploadBinaryHelper helps with uploading binary files. The Picture Upload sample app shows how to use this function.
Parameters
The function has the following parameters:
datasource
An Appery.io REST service instance with POST method to create a file in Files collection.
Yes.
imageBase64
A base64 string of the image.
Yes.
name
A name with which file will be stored. If empty, current date will be used as name.
No.
type
Image format as .jpg or .png. If empty .jpg is used.
No.
Examples
More examples using JavaScript API.
More examples using Appery.io JavaScript API for jQuery Mobile app.
If component1 is the component name, then to hide/show an element:
Apperyio('component1').hide();
Apperyio('component1').show();
Both Hide () and Show() are standard jQuery functions. If component1 is the component ID:
$('#component1').hide();
$('#component1').show();
Check If an Element Is Visible
Every component has Visible property in the Properties panel:
When the Visible property is unchecked there is a CSS rule for this element:
display: none
// Check visibility with JavaScript
if (Apperyio('mobilebutton_10').css('display') == 'none')
{
console.log('Hidden');
}
else
{
console.log('Visible');
}