restdb.io Cheat Sheet (v0.
2)
To make life easier for restdb.io developers, we have assembled a compact version of our docs for
reference. Here you'll find reference to the Collection API, the Media Content API, the Meta data API, Mail
API, Authentication API and the Codehook APIs.
Database REST API URLs are prefixed with the full database name.
https://{db-name}.restdb.io/rest/{collection}[.<format>]?q={}&h={}&...
For example, a query against the customer collection in the database mydb-fex0:
https://mydb-fex0.restdb.io/rest/customers?q={"name": "Jane"}
Data Collection API
Operation Resource Description
Get list of JSON documents from
GET /rest/{collection}
database collection.
Get one document from a
GET /rest/{collection}/ID collection. ID must be a valid
ObjectID.
Get list of documents from
GET /rest/{collection}/ID/{subcollection} subcollection (subcollection is field
name of type child).
Get document from subcollection
GET /rest/{collection}/ID/{subcollection}/ID (subcollection is field name of type
child) and ID is a valid ObjectID.
Create a new document in a
POST /rest/{collection} collection. Request body is a valid
JSON document.
Create a child document in a sub
POST /rest/{collection}/ID/{subcollection}
collection.
Post array data as a bulk operation.
Request body is an array of JSON
documents, e.g. [{},{},{}].
POST
/rest/{collection} Apply an optional parameter ?
array
validate=false, for high speed
bulk inserts without validation. Will
also work for child documents.
1/9
Operation Resource Description
Update a document in a collection.
PUT /rest/{collection}/ID Request body is a valid JSON
document.
Update one or more properties on
a document in a collection.
PATCH /rest/{collection}/ID
Request body is a valid JSON
object.
DELETE /rest/{collection}/ID Delete a document in a collection.
Delete an array of documents in a
DELETE
/rest/{collection}/* collection. Request body must be
array
an array of ID's.
Delete a list of documents in a
collection. List is based on query in
DELETE
/rest/{collection}/*?q={...} parameter ?q={...}. Only
query
allowed with a full access API-key
or from a Codehook.
Parameters for GET operations
Parameter Description
Database query as a valid JSON string:
q /rest/people?q={"firstname":"Karen", "lastname":"Johnson", age:
39}
Query hints to specify: fields, max, skip and orderby. Aggregation parameters can also be
specified as hints, read more here :
h
/rest/people?q={}&h={"$fields":
{"title":1},"$max":10,"$skip":5,"$orderby":{"body":1}}
Performs a text search and retrieves all matching documents:
filter
/rest/people?q={}&filter=johnson
Specifies which field(s) should be used to sort the result. You can add multiple fields by
sort simply adding another sort parameter. Default sort=_id:
/rest/people?q={}&sort=lastname
Sort direction. Allowed values are 1 (ascending) and -1 (descending). Used together with
dir sort. Multiple dir parameters can be used in conjunction with sort:
/rest/people?q={}&sort=lastname&dir=-1
Where to start in the result set. Used for paging:
skip
/rest/people?skip=100
Maximum number of records retrieved:
max
/rest/people?max=20
2/9
Parameter Description
Returns an object with both data and total count. Totals equals to max parameter or
default 1000:
totals
Output from query /rest/people?totals=true returns the object {data: [ … ],
totals: { total: 100, count: 40, skip: 0, max: 1000}}
Returns an object with no data and just the total count:
totals and
/rest/people&totals=true&count=true, output from query -> {data: [],
count
totals: { count: 42}}
Displays internal restdb.io fields (_keywords, _tags, _version, _created, _createdby,
metafields _mock):
/rest/people?metafields=true
Group output from query by a field:
groupby
/rest/people?groupby=gender
Perform aggregation function on data groups. Useful together with groupby parameter.
Avaliable functions; SUM, AVG, MIN, MAX and COUNT Docs:
aggregate
/rest/people?
groupby=gender&aggregate=SUM:weight&aggregate=AVG:age
Output format from request. .html returns a standard markup for all fields. .js (Javascript)
returns a script that can be included in a web page for search engine indexing. .json
format
standard JSON format:
/rest/people.html
A valid apikey, full access key or a CORS enabled key:
apikey /rest/people?&apikey=4321fd234f0876....
Not recommended for production. Use header field x-apikey instead
Inserts canonical URLs for image references and object references:
idtolink
/rest/people?idtolink=true
Used together with idtolink. Extract links as properties on root object:
flatten
/rest/people?flatten=true
Return all items that refers to a record. Requires a record _id in the query or path:
referencedby
/rest/people/56011150e1321c7300000001?referencedby=true
Replace media ID's with a full record from the media archive:
fetchmediadata
/rest/people?fetchmediadata=true
Insert records from parent-child relation on parent record:
fetchchildren
/rest/company?fetchchildren=true
Data aggregation API
Function Format Comment Example
Min MIN:field Returns object h={"$aggregate":["MIN:score"]}
3/9
Function Format Comment Example
Max MAX:field Returns object h={"$aggregate":["MAX:score"]}
Avg AVG:field Returns value h={"$aggregate":["AVG:score"]}
Sum SUM:field Returns value h={"$aggregate":["SUM:score"]}
Returns value with chosen h={"$aggregate":
Count COUNT:property
property name ["COUNT:nplayers"]}
$groupby:
Groupby Returns "groupkey":[array] h={"$groupby":["category"]}
["field", ...]
$groupby: Predefined values for:
Groupby h={"$groupby":
["$YEAR:field", $YEAR, $MONTH, $DAY,
(dates) ["$YEAR:registered"]}
...] $HOUR, $SEC
Groupby
$groupby: Format strings for: ss, hh,
(dates h={"$groupby":
["$DATE:format", mm, dd, MM, YY. All
with ["$DATE.MMM:registered"]}
...] formats at momentjs.com
formats)
h={"$groupby":["category"],
Grand $aggregate- Recursive aggregation
"$aggregate": ["AVG:score"],
totals grand-total: true functions of groups
"$aggregate-grand-total": true}
Media Content API
Operation Resource Description
Get binary data for media object with ID. ID is a valid ObjectID for an
object in the media archive or an existing filename. Parameter s options;
GET /media/ID ?s=t (thumbnail), ?s=w (web) and ?s=o (original size). No API-key
required. Use parameter ?download=true if you want the image or
file to be downloaded instead of displayed.
GET /media/ID/meta Get JSON structure with media object metadata. Requires API-key.
Post file(s) using the multipart/formdata protocol, view
POST /media
example. Requires API-key.
PUT /media Not yet implemented
DELETE /media/ID Delete media content with ID. Requires API-key.
Meta Data API
Operation Resource Description
GET /rest/_meta Get meta data for the database as a JSON object.
4/9
Operation Resource Description
GET /rest/{collection}/_meta Get meta data for the collection as a JSON object.
Mail API
Operation Resource Description
Send email. Request body contains one document:
{"to": "...", "subject": "...", "html": "...", "company":
POST /mail
"...", "sendername": "..."}
, or an array of documents [{…},{…}]
Authentication API
Operation Resource Description
Generate a new JWT token. Body must contain a path to a secret and a
POST /auth/jwt payloan with JWT claims, e.g {"secret": "path from global
settings", "payload": {"email": "xxx@example.com"}}
GET /auth/userinfo Get data about a user. Returns email, displayname and image.
Logout a user, invalidates the login token. This token can no longer be
POST /auth/logout
used for API access.
Codehook API
Database operation hooks
Codehook Available parameters Description
req.query, req.hint, res.end([optional
beforeGET(req, res) Called before a GET operation
error])
beforePUT(req, res) req.body, res.end([optional error]) before a PUT
afterPUT(req, res) req.body, req.result after a PUT
beforePOST(req, res) req.body, res.end([optional data, error]) before a POST
afterPOST(req, res) req.body, req.result, res.end() after a POST
beforeDELETE(req,
req.body, res.end([optional error]) before a DELETE
res)
afterDELETE(req, res) req.body after a DELETE
beforePATCH(req, res) req.body, res.end([optional error]) before a PATCH
afterPATCH(req, res) req.body, req.result after a PATCH
5/9
Codehook Available parameters Description
triggers on a crontab
runJob(req, res) res.end("Optional message to log")
expression
Codehook database API
Function Parameters Description
get operation to the current database.
db.get(path, path: REST url, query: query object,
E.g. db.get('/rest/customer',
query, hint, hint: hint object, callback:
{}, {}, function(error, data)
callback) function(error, data)
{...}
db.put(path, path: REST url, data: JSON, callback:
put operation to the current database
data, callback) function(error, data)
db.patch(path, path: REST url, data: JSON, callback:
patch operation to the current database
data, callback) function(error, data)
db.post(path, path: REST url, data: JSON, callback:
post operation to the current database
data, callback) function(error, data)
db.delete(path, path: REST url, data: JSON, callback:
delete operation to the current database
data, callback) function(error, data)
Codehook network API
Function Parameters Description
request(options,
options: json, callback(error, response, body) Network API
callback)
slack(options, options: message, slackhookurl, channel, callback: Send a message to
callback) function(result) Slack
sendMail(options, options: to, subject, html, company, callback:
Send a html email
callback) function(result)
Codehook utility function API
Function Parameters Description
Variable list of
arguments log.info,
log.debug(str, ...) Writes output to Rest inspector
log. debug, log. error,
log.fatal
async.series(funcarray, Call an array of functions in a sequence and
Array of functions
callback) callback when all are done. See examples.
6/9
Function Parameters Description
First function calls next etc. in sequence
async.waterfall(funcarray,
Array of functions passing parameters along and finally
callback)
callback when all are done. See examples.
Creates a continuation function with some
async.apply(function, Apply one function
arguments already applied. Add to array and
arguments) with arguments
use with async.series. See examples.
Run Handlebars on
template(str, context) str with context json Handlebars templating function
data
Run Markdown
markdown(str) Returns valid HTML
parser on str
auth.decode_jwt(token,
A valid JWT token callback with (err, decodedjwt) as arguments
callback)
auth.verify_jwt(token, A valid JWT token
callback with (err, decodedjwt) as arguments
secret, callback) and your secret
token-string, secret-
verifyHash(token, secret, Verify crypto tokens, e.g. Shopify webhook
string, algorithm,
'RSA-SHA256', 'base64'); token
encoding
Server Pages
Use these Handlebars helper tags inside RestDB Pages.
Helper tag Description
Run database queries and bind data to the Page view context.
{#context}
{
"mydata": {
"collection": "contacts",
{{#context}} "query": {"name": "jane"},
"hints": {"$orderby": {"name": 1}}
}
}
{/context}
...
Reuse another Page as a fragment in another.
{{include}}
...<div>{{include "mypagename"}}</div>...
7/9
Helper tag Description
Place output in inherited master page layout block.
{{#inherit "masterpagename"}}
{{#inherit}}, {{#block "blockname"}}
{{#block}} ...
{/block}
{{/inherit}}
Logic statement.
{{#ifcond val1 '==' val2}}
{{val1}} is equal to {{val2}}.
{{#ifCond}}
{{else}}
{{val1}} and {{val2}} are not equal.
{{/ifcond}}
Output encoded JSON.
{{tojson}}
{{tojson val}}
Output un-encoded JSON.
{{rawjson}}
{{torawjson val}}
Date functions from the moment.js library.
{{moment}}
{{moment dateval format="YYYY DD MM hh:mm:ss"}}
Password protect pages.
{{#auth}}
{{auth}}
{"password": "secret", "user": "jane"}
{{/auth}}
Substring; start, stop, overflow symbol.
{{trimstring}}
{{trimString str 0 50 '..'}}
Number decimal format.
{{fixednumber}}
{{fixedNumber anumber 4}}
String functions from lodash.com library.
{{_ ...}}
{{_ "upperCase" str}}
Render text as Markdown.
{{markdown}}
{{markdown mdvariable}}
Sort an array in ascending order.
{{#sortBy list "field"}}
{{#sortby}}
{{#each .}}...{{/each}}
{{/sortBy}}
{{#sortbydesc}} Sort an array in decending order, see sortby.
Parse string to an Integer.
{{parseint}}
{{parseInt astring -1}}
8/9
Helper tag Description
Switch case statement.
{{#switch field}}
{{#case 'A'}}Case A.{{/case}}
{{#switch}} {{#case 'B' 'C'}}Case B and C.{{/case}}
{{#default}}Any other case with value {{field}}.
{{/default}}
{{/switch}}
Page Codehooks, serverless Javascript functions. Bind output from function to Page
context.
{(#codehook}} {{#codehook code="aPageCodeHook.js"}}
Inside scope of codehook with {{field}} set by script.
{{/codehook}}
URL parameters for a Page.
{{params}}
{{params.title}}
URL path variables.
{{pathparams}} Page routes like: "/contacts/:name" can be access with
{{pathparams.name}}
Global settings properties for current database.
{{settings}}
{{settings.val}}
restdb.io is a fast and simple NoSQL cloud database service. With restdb.io you get schema, relations,
REST API and an efficient multi-user admin UI for working with data. Our customers use it for backends,
business databases, API-first CMS, data collection and much more. It is easy to get started with the free
development plan.
9/9