Getting Help
Technical Questions
For questions related to our API, SDKs, or general technical help, use the Stamplay tag on Stackoverflow.
After posting on Stackoverflow, adding the link to your question in our Slack Community will allow other Stamplayers the opportunity to provide any insight into your question.
Discussion and Feedback
To discuss Stamplay with other Stamplayers, give feedback, report bugs, or submit feature requests, join our Slack Community.
For account related questions, submit a ticket to support@stamplay.com.
Contributing
Our documentation is open source! This means if you would like to contribute to our community, tidy up or add a better example/explanation for a problem you've solved, suggest new content sections or just fix a typo, you can.
To contribute, checkout the repo to find out how get things setup in your local enviornment, and learn about our contribution guidelines, see our Github.
Quickstart
Create An Account
The first thing needed to get started with Stamplay is to signup for a free account.
After signing up, create your first Stamplay application in the dashboard by entering a name for your application in the input and selecing CREATE.
Install CLI
npm install -g stamplay-cli
The Stamplay CLI will allow you to run your application locally, manage application versioning, deploy to the cloud, etc.
Ensure you have Node.js & NPM installed, then npm install
the stamplay-cli
package globally.
After installing the CLI, initialize a project locally inside a project folder by running an init
command from the stamplay
CLI.
stamplay init
You will be prompted to enter an APP ID
and API KEY
for a Stamplay application. These can be found in the Dashboard of the application created in the previous step.
stamplay start
To run our application locally, run the start
command from the stamplay
CLI.
Setup
bower install stamplay-js-sdk
Stamplay.init("APP-ID")
The Stamplay JavaScript SDK is a client-side library for interacting with Stamplay.
Run bower install
for the stamplay-js-sdk
package to download from bower
into your local project directory.
To initialize the library, run the init
method from the Stamplay
SDK.
For REST API Quickstart proceed to the next step, otherwise select the JavaScript tab for the SDK quickstart instructions for this step.
Define Schema
Create a new Object schema by visiting the Object section within the editor for your application through the sidebar.
Inside the Object section, add a name and data type for each property on the schema desired and Save.
Write Data
curl -X "POST" "https://APP-ID.stamplayapp.com/api/cobject/v1/car" \
-H "Content-Type: application/json" \
-d "{\"make\":\"Volkswagen\",\"model\":\"Jetta\",\"year\":2013,\"color\":\"silver\",\"top_speed\":140}"
var car = {
make : "Volkswagen",
model : "Jetta",
year : 2013,
color : "silver",
top_speed : 140
}
Stamplay.Object("car").save(car)
.then(function(res) {
// success
}, function(err) {
// error
})
To write data to Stamplay, model an object after the schema just created.
Pass the object into the save
method on the Stamplay.Object
class.
Most every SDK method returns a promise, or you can pass a callback in as the last method argument.
To write data, send a JSON object modeled after the schema in a POST
request body to the API Object resource.
Read Data
Stamplay.Object("car").get({})
.then(function(res) {
// success
}, function(err) {
// error
})
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/car"
To fetch Object data from Stamplay, use the get
method on the Stamplay.Object
class.
The get
method takes an options object. The object is matched against all records, and returns only those that match.
To read object data, send a GET
request to the API Object resource.
Register Users
var credentials = {
email : "user@provider.com",
password : "123123"
};
Stamplay.User.signup(credentials)
.then(function(res) {
// success
}, function(err) {
// error
})
curl -X "POST" "https://APP-ID.stamplayapp.com/api/user/v1/users" \
-H "Content-Type: application/json" \
-d "{\"email\":\"user@stamplay.com\",\"password\":\"my_password\"}"
To register a user with a local account, no additional setup within the Stamplay editor is required.
Use the signup
method on the the Stamplay.User
class, and pass in an object with at least an email
and password
property.
To register, send a POST
request to the API User resource, with a JSON object that has an email
and password
property, in the request body.
Login Users
To login a user to a local account, use the login
method on the Stamplay.User
class.
To login a user to a local account, send a POST
request with JSON object in the body, that contains an email
and password
of a registered account.
var credentials = {
email : "user@provider.com",
password : "123123"
}
Stamplay.User.login(credentials)
.then(function(res) {
// success
}, function(err) {
// error
})
curl -X "POST" "https://APP-ID.stamplayapp.com/auth/v1/local/login" \
-H "Content-Type: application/json" \
-d "{\"email\":\"user@stamplay.com\",\"password\":\"my_password\"}"
Deploy
To deploy your application, run the deploy
command from the stamplay
CLI.
stamplay deploy
After deployment is finished, your application will be live at [YOUR APP ID].stamplayapp.com.
API Overview
Summary
The Stamplay API exposes the following resources:
Resource | Endpoint |
---|---|
Objects | /api/cobject/v1/:cobjectId |
Users | /api/user/v1/users |
Roles | /api/user/v1/roles |
Code Blocks | /api/v1/run/:codeblockId |
Stripe | /api/stripe/v1/ |
Pagination
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie?page=2&per_page=30"
Stamplay.Object("movie").get({
page : 2,
per_page : 30
}).then(function(res) {
// success
}. function(err) {
// error
})
Stamplay.Object("movie").get({
page : 2,
per_page : 30
}, function(err, res) {
// response
})
Responses from the User and Object resource will also return a pagination
object.
Pagination can be managed by using the page
and per_page
query parameters. The maximum per_page
value allowed is capped at 250
. This means that any per_page
value beyond that will always return 250
results.
Pagination details are included using the Link header introduced by RFC 5988. The Link header returns a set of ready-made links so the API consumer does not have to construct the links themselves.
{
"data": [],
"pagination": {
"page": 1,
"per_page": 20,
"total_pages": 4,
"total_elements": 71
}
}
Default pagination attribute values:
Property | Type | Default |
---|---|---|
page | Number | 1 |
per_page | Number | 20 |
total_pages | Number | total_elements / per_page |
total_elements | Number | total of the type queried |
Filtering
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/picture?status=published"
Stamplay.Object("picture")
.get({ status : "published" })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object('picture')
.get({ status : "published" }, function(err, res) {
// response
})
To filter a response based on a value of a field, set the field and value as a parameter in the request. To filter by more than one field, add each filterable field to the request as a paramter.
Default properties available to filter by:
Property | Type |
---|---|
dt_create | Date |
dt_update | Date |
_id | MongoID (String) |
Any property on a data structure is filterable, the above only contain the absolute base structure which is always present on a Stamplay database record.
Sorting
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie?sort=-dt_create"
Stamplay.Object("movie").get({ sort : "-dt_create" })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object('movie')
.get({ sort : "-dt_create" }, function(err, res) {
// response
})
To sort the response, set a sort
parameter as a comma delimited list to sort by in order of importance.
If a field name is appened to an -
character then that field will be sorted in descending order based on the type, otherwise by default the field will be sort in ascending order.
Default properties available to sort by:
Property | Data Type | Sort By : Default - Ascending |
---|---|---|
dt_create | Date | |
dt_update | Date | |
_id | MongoID (String) |
Selecting
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie?select=-dt_create,owner,title"
Stamplay.Object("movie").get({ select : "dt_create,owner,title" })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object('movie')
.get({ sort : "dt_create,owner,title" }, function(err, res) {
// response
})
Selecting is the response projection for each object returned. This allows for a lighter data transfer between requests, and simplifies response objects.
To select a field to return, set the select
request parameter to the value of the field name to return. If you want to return more than one field, set the select
parameter as a comma delimited set of properties to return.
The _id
field is always returned.
Default return properties:
By default all properties are returned.
Populating References
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie?populate=true"
Stamplay.Object("movie")
.get({ populate : true })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object('movie')
.get({ populate : true }, function(err, res) {
// response
})
To populate reference fields in the response, add the populate
parameter to the request URI as true
.
To populate reference fields in the response, add the populate
property to the get
SDK method options object.
Advanced Queries
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"rating":\{"$gt":5\}\}'
Stamplay.Object("movie")
.get({ where : JSON.stringify({ rating : { $gt : 5 } }) })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object('movie')
.get({ where : JSON.stringify({ rating : { $gt : 5 } }) }, function(err, res) {
// response
})
For more advanced methods of queries, Stamplay supports an array of MongoDB's conditional operators.
By setting a JSON query string to the where
parameter you can use the operators to perform advanced queries.
Operator | Summary |
---|---|
$gt | Matches values that are greater than the value specified in the query. |
$gte | Matches values that are greater than or equal to the value specified in the query. |
$in | Matches any of the values that exist in an array specified in the query. |
$lt | Matches values that are less than the value specified in the query. |
$lte | Matches values that are less than or equal to the value specified in the query. |
$ne | Matches all values that are not equal to the value specified in the query. |
$nin | Matches values that do not exist in an array specified to the query. |
$or | Joins query clauses with a logical OR returns all documents that match the conditions of either clause. |
$and | Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. |
$not | Inverts the effect of a query expression and returns documents that do not match the query expression. |
$nor | Joins query clauses with a logical NOR returns all documents that fail to match both clauses. |
$exists | Matches documents that have the specified field. |
$type | Selects documents if a field is of the specified type. |
$all | Matches arrays that contain all elements specified in the query. |
$elemMatch | Selects documents if element in the array field matches all the specified $elemMatch condition. |
$size | Selects documents if the array field is a specified size |
$regex | Selects documents where values match a specified regular expression. |
Authorization
"Authorization" : "Basic c3RhbXBsYXlrYjo5MTRhMmUzMaMwZWRlMDdmZThhNjYzMzkxMWQyYWQyOTNkNjJkNTQ3OGFiYmViNjEyNzhhYjFjYzE2MDhiZaRi"
"x-stamplay-jwt" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoidXNlciIsImFwcERvbWFpbiI6InN0YW1wbGF5a2Iuc3RhbXBsYXlscHAuY29tIiwiYXBwSWQiOiJzdGFtcGxheWtiIiwidXNlciI6IjU2ZjAyZDY0NjFkNWI0MTA1ZDFhMjY4NCIsImlhdCI6MTQ1ODU4MTQwNiwiZXhwIjoxNDU5MTg2Mjc4fQ.UDFUe0Zb2ZHx3HXdiUXWnHSyKghVI_harpkkyC3BU8A"
Depending on the origin enviornment of a request to Stamplay, the method of authenticating the request differs.
Client side requests can be authenticated by setting the x-stamplay-jwt
header as the JSON Web Token issued when a user authenticates with an email and password, or social provider.
Server side request can be authenticated by setting the Authorization
header as Basic AppId:ApiKey
. The AppId:ApiKey
are to be set as a base64 encoding.
CORS Policy
Stamplay uses a selective cross-origin resource sharing (CORS) policy, meaning that you may only make requests to the Stamplay from an origin that has been previously declared.
This is made to govern which origins are authorized and which are not. By default only the base URL ending with .stamplayapp.com
is the one allowed to send requests.
To enable other CORS enabled domains, visit the Dashboard -> Settings section in the Stamplay Editor.
Allowed HTTP Requests
Method | Summary |
---|---|
GET | Get a resource or list of resources |
POST | Create a resource |
PUT | Update a resource |
PATCH | Update a resource partially |
DELETE | Delete a resource |
Error Codes
Status Code | Status Text | Summary |
---|---|---|
200 | OK | The request was successful. |
201 | Created | The request was successful and a resource was created. |
204 | No Content | The request was successful but there is no representation to return (i.e. the response is empty). |
400 | Bad Request | The request could not be understood or was missing required parameters. |
401 | Unauthorized | Authentication failed or the user request the resource doesn’t have the required permissions for reqested operation. |
403 | Forbidden | Access denied, Authentication will not help. |
404 | Not Found | Resource not found. |
405 | Method Not Allowed | Requested method is not supported for resource. |
500 | Internal Server Error | Something went wrong during your request |
SDK and Client Libraries
Javascript SDK
bower install stamplay-js-sdk
Stamplay.init('APPID');
Refer to the NodeJS section below
The JavaScript SDK is a client side library to help simplify interacting with the Stamplay API. It is available both on npm
and bower
.
To install the JavaScript SDK, run bower install stamplay-js-sdk
.
To initialize the SDK within your client side enviornment, run the init
method on the Stamplay
global object. Ensure the module has been included before running the method, and pass in your APP ID
as the sole method argument.
An additional options object can be passed in as the second argument, but is primarily meant for use within a mobile application.
Our JavaScript SDK is open source on Github!
JavaScript API Reference
The JavaScript SDK exposes the following components and methods:
Users
User | Stamplay.User |
---|---|
save | save(data, [callback]) |
get | get(data, [callback]) |
getById | getById(id, data, [callback]) |
remove | remove(id, [callback]) |
update | update(id, data, [callback] ) |
currentUser | currentUser([callback]) |
login | login(data, [callback]) |
socialLogin | socialLogin(provider) |
signup | signup(data, [callback]) |
logout | logout() |
resetPassword | resetPassword(data, [callback]) |
getRoles | getRoles([callback]) |
getRole | getRole(id, [callback]) |
setRole | setRole(id, roleId, [callback]) |
Objects
Object | Stamplay.Object("cobject") |
---|---|
save | save(data, [callback]) |
get | get(data, [callback]) |
getById | getById(id, data, [callback]) |
remove | remove(id, [callback]) |
update | update(id, data, [callback]) |
patch | patch(id, data, [callback]) |
findByCurrentUser | findByCurrentUser([attr], [data], [callback]) |
upVote | upVote(id, [callback]) |
downVote | downVote(id, [callback]) |
rate | rate(id, rate, [callback]) |
comment | comment(id, text, [callback]) |
push | push(id, attribute, data, [callback]) |
Code Blocks
Code Block | Stamplay.Codeblock("codeblock") |
---|---|
post | post( data, queryParams, [callback]) |
put | put( data, queryParams, [callback]) |
patch | patch( data, queryParams, [callback]) |
get | get( queryParams, [callback]) |
delete | delete( queryParams, [callback]) |
Webhooks
Webhook | Stamplay.Webhook("webhook") |
---|---|
post | post(data, [callback]) |
Stripe
Stripe | Stamplay.Stripe |
---|---|
charge | charge(userId, token, amount, currency, [callback]) |
createCreditCard | createCreditCard(userId, token, [callback]) |
createCustomer | createCustomer(userId, [callback]) |
createSubscriptionuserId | createSubscriptionuserId, planId, [callback]) |
deleteSubscription | deleteSubscription(userId, subscriptionId, options, [callback]) |
getCreditCard | getCreditCard(userId, [callback]) |
getSubscription | getSubscription(userId, subscriptionId, [callback]) |
getSubscriptions | getSubscriptions(userId, options, [callback]) |
updateCreditCard | updateCreditCard(userId, token, [callback]) |
updateSubscription | updateSubscription(userId, subscriptionId, options, [callback]) |
Queries
Query | Stamplay.Query("type", "resource") |
---|---|
greaterThan | greaterThan(attr, value) |
greaterThanOrEqual | greaterThanOrEqual(attr, value) |
lessThan | lessThan(attr, value) |
lessThanOrEqual | lessThanOrEqual(attr, value) |
pagination | pagination(page, per_page) |
between | between(attr, value1, value2) |
equalTo | equalTo(attr, value) |
notEqualTo | notEqualTo(attr, value) |
exists | exists(attr) |
notExists | notExists(attr) |
sortAscending | sortAscending(attr) |
sortDescending | sortDescending(attr) |
populate | populate() |
populateOwner | populateOwner() |
select | select(attr,…) |
regex | regex(attr, regex, options) |
near | near(type, coordinates, maxDistance, minDistance) |
nearSphere | nearSphere(type, coordinates, maxDistance, minDistance) |
geoIntersects | geoIntersects(type, coordinates) |
geoWithinGeometry | geoWithinGeometry(type, coordinates) |
geoWithinCenterSphere | geoWithinCenterSphere(coordinates, radius) |
or | or(query,..) |
exec | exec([callback]) |
NodeJS SDK
npm install stamplay
Refer to the Javascript section above
const Stamplay = require("stamplay");
const stamplay = new Stamplay("APPID", "APIKEY");
The Node.js SDK is a server side library to help simplify admin interaction with the Stamplay API.
To install the Node.js SDK, run npm install stamplay
.
To initialize the SDK within your server side enviornment, first require
the module, then create a new instance of the module require and pass in your APP ID
and API KEY
credentials as seperate arguments.
Our Node.js SDK is open source on Github!
Node.js API Reference
The JavaScript SDK exposes the following components and methods:
Users
User | Stamplay.User |
---|---|
save | save(data, [callback]) |
get | get(data, [callback]) |
remove | remove(id, [callback]) |
update | update(id, data, [callback] ) |
Objects
Object | Stamplay.Object("cobject") |
---|---|
save | save(data, [callback]) |
get | get(data, [callback]) |
remove | remove(id, [callback]) |
update | update(id, data, [callback]) |
patch | patch(id, data, [callback]) |
upVote | upVote(id, [callback]) |
downVote | downVote(id, [callback]) |
rate | rate(id, rate, [callback]) |
comment | comment(id, text, [callback]) |
push | push(id, attribute, data, [callback]) |
Code Blocks
Code Block | Stamplay.Codeblock("codeblock") |
---|---|
run | run(data, queryParams, [callback]) |
Webhooks
Webhook | Stamplay.Webhook("webhook") |
---|---|
post | post(data, [callback]) |
Stripe
Stripe | Stamplay.Stripe |
---|---|
deleteCustomer | deleteCustomer(userId, [callback]) |
createSubscriptionuserId | createSubscriptionuserId, planId, [callback]) |
deleteSubscription | deleteSubscription(userId, subscriptionId, options, [callback]) |
getSubscription | getSubscription(userId, subscriptionId, [callback]) |
getSubscriptions | getSubscriptions(userId, options, [callback]) |
updateSubscription | updateSubscription(userId, subscriptionId, options, [callback]) |
Queries
Query | Stamplay.Query("type", "resource") |
---|---|
greaterThan | greaterThan(attr, value) |
greaterThanOrEqual | greaterThanOrEqual(attr, value) |
lessThan | lessThan(attr, value) |
lessThanOrEqual | lessThanOrEqual(attr, value) |
pagination | pagination(page, per_page) |
between | between(attr, value1, value2) |
equalTo | equalTo(attr, value) |
notEqualTo | notEqualTo(attr, value) |
exists | exists(attr) |
notExists | notExists(attr) |
sortAscending | sortAscending(attr) |
sortDescending | sortDescending(attr) |
populate | populate() |
populateOwner | populateOwner() |
select | select(attr,…) |
regex | regex(attr, regex, options) |
near | near(type, coordinates, maxDistance, minDistance) |
nearSphere | nearSphere(type, coordinates, maxDistance, minDistance) |
geoIntersects | geoIntersects(type, coordinates) |
geoWithinGeometry | geoWithinGeometry(type, coordinates) |
geoWithinCenterSphere | geoWithinCenterSphere(coordinates, radius) |
or | or(query,..) |
exec | exec([callback]) |
Users
The base user data structure:
Property | Summary |
---|---|
_id | a unique identifier |
displayName | the user's displayName |
name | the user's name |
the user's email | |
identities | an object that contains social informations provided by the third party authentication services |
dt_create | a date that represent the user's signup date |
dt_update | a date that represent the last time the user has been updated |
givenRole | the role'sunique id |
The User data collection is schemaless, meaning that properties can be added on the go without adding them to a defined schema with specific property data types.
Local Authentication
A local authentication flow for login and signups is baked in to every Stamplay application.
Signup
curl -X "POST" "https://APP-ID.stamplayapp.com/api/user/v1/users" \
-H "Content-Type: application/json" \
-d "{\"email\":\"user@stamplay.com\",\"password\":\"my_password\"}"
var credentials = {
email : "user@stamplay.com",
password : "my_password"
}
Stamplay.User.signup(credentials)
.then(function(res) {
// success
}, function(err) {
// error
})
var credentials = {
email : "user@stamplay.com",
password : "my_password"
}
Stamplay.User.save(credentials, function(err, res) {
// response
})
The JSON response looks like.
{
"__v":0,
"email":"user@stamplay.com",
"password":"$2a$12$ERoo1bSRttQm9zLRkJIpnO9tgjtTnFRUt/57R.gLhnJor1RYkzUBS",
"givenRole":"561c001ce57bdca90ee4482b",
"appId":"stamplaykb",
"_id":"570eca8ec0d4b16b26a4bbe0",
"dt_update":"2016-04-13T22:39:10.621Z",
"dt_create":"2016-04-13T22:39:10.621Z",
"emailVerified":true,
"verificationCode":"98175bf31b80f59e2956",
"profileImg":"",
"id":"570eca8ec0d4b16b26a4bbe0"
}
Sign up a user for a local user account.
Attribute | Optional | |
---|---|---|
email |
a valid email address | |
password |
user provided secret |
Login
curl -X "POST" "https://APP-ID.stamplayapp.com/auth/v1/local/login" \
-H "Content-Type: application/json" \
-d "{\"email\":\"user@stamplay.com\",\"password\":\"my_password\"}"
var credentials = {
email : "user@stamplay.com",
password : "my_password"
}
Stamplay.User.login(credentials)
.then(function(res) {
// success
}, function(err) {
// error
})
// no method
The JSON response looks like.
{
"_id":"570eca8ec0d4b16b26a4bbe0",
"email":"user@stamplay.com",
"password":"$2a$12$ERoo1bSRttQm9zLRkJIpnO9tgjtTnFRUt/57R.gLhnJor1RYkzUBS",
"givenRole":"561c001ce57bdca90ee4482b",
"appId":"stamplaykb",
"__v":0,
"username":"",
"displayName":"",
"dt_update":"2016-04-13T22:39:10.893Z",
"dt_create":"2016-04-13T22:39:10.621Z",
"emailVerified":true,
"verificationCode":"98175bf31b80f59e2956",
"profileImg":"",
"id":"570eca8ec0d4b16b26a4bbe0"
}
Login a user to a local account.
Attribute | Optional | |
---|---|---|
email |
a valid email address | |
password |
user provided secret |
Social Authentication
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/:provider/connect"
Stamplay.User.socialLogin("provider")
// no method
Response is a redirect, as specified in the Authentication section, on social login success.
Authentication via an array of different social provider is possibled by some minor configuration with the Stamplay editor, and a simple request to the Stamplay API.
Attribute | Optional | |
---|---|---|
provider |
the slug identifier of the social provider |
Ionic Integration
Stamplay.init("APP-ID", {
isMobile: true,
absoluteUrl : true,
autorefreshSocialLogin : false
})
Login users with social accounts inside an Ionic mobile application.
To use a social provider within an Ionic application, you must pass in an additonal options object in the Stamplay.init
method when intializing the SDK.
Attribute | Optional | |
---|---|---|
isMobile |
manages the login/signup behavior for hybrid environments like Ionic, if true opens auth dialog in new window. | |
absoluteUrl |
force the path to be absolute | |
autorefreshSocialLogin |
refresh application after a successful socialLogin |
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/facebook/connect"
Stamplay.User.socialLogin("facebook")
// no method
Login a user with a Facebook account.
Create a Facebook App
1.1. Go to Facebook developers.
1.2. In the upper right corner, click on Add a New App.
1.3. Choose the type of app you want to create.
1.4. Name your Facebook App and select Create Facebook App Id.
1.5. Skip the Quick Start by clicking on the button in the upper right corner.
Configure the Facebook App Settings
2.1. Click on Settings in the left menu.
2.2. Click on + Add Platform.
2.3. Fill the Site Url field with your Stamplay domain: https://APP-ID.stamplayapp.com (and/or your custom domain if you have a paid plan).
2.4. From the Settings view click on the Advanced tab and type in the OAuth Redirect URIs the following: https://APP-ID.stamplayapp.com/auth/v1/facebook/callback and https://localhost:8080/auth/v1/facebook/callback so that you can also test the signup flow locally when using Stamplay Command Line.
Add the Facebook Integration to Stamplay
3.1. Copy the App Id
and App Secret
from the Facebook App and add the values to the corresponding field inside the Stamplay editor in the Users - Authentication section.
3.2. To test the social login integration, copy and paste this link with your APP ID
into a browser: https://APP-ID.stamplayapp.com/auth/v1/facebook/connect. After connecting your account, check the DATA section to inspect the new User record created.
3.3. The steps covered in this guide are not enough to have a Facebook app approved for production. You need to provide other information and submit the app for review; the process can take many days to complete. Refer to Facebook documentation for more information.
Stamplay asks for the following permissions:
public_profile
email
user_friends
We store data from public_profile
and email
. Refer to the Facebook documentation for more information.
Google+
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/google/connect"
Stamplay.User.socialLogin("google")
// no method
Login a user with a Google+ account.
Create a Google Client Id
1.1. Go to https://code.google.com/apis/console and create an APIs project.
1.2. Click on Credentials from the API & Auth section of the left menu.
1.3. Click on Create new Client Id button.
Configure the Client ID
2.1. Choose the type Web application and click on Configure Consent Screen button.
2.2. Add the required information to the consent screen and save.
2.3. Fill in the Authorized Javascripts Origins field with your Stamplay domain: https://APP-ID.stamplayapp.com (and/or your custom domain if you have a paid plan).
2.4. Fill in the Authorized Redirect URIs field with the following value: https://APP-ID.stamplayapp.com/auth/v1/google/callback.
2.5. Click on Create client ID
Add the Google+ Integration To Stamplay
3.1. Copy the Client Id and Client Secret from the Google App and add the values to the Stamplay app.
3.2. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/google/connect.
3.3. Then click on Users in the left menu of the Editor to browse the data fetched.
Stamplay asks for the following permissions:
userinfo.profile
userinfo.email
Refer to the Google documentation for more information.
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/twitter/connect"
Stamplay.User.socialLogin("twitter")
// no method
Login a user with a Twitter account.
Create a Twitter app
1.1. Go to https://apps.twitter.com/app/new to create a new Twitter app.
Configure the app
2.1. Fill in name and description.
2.2. Fill in the Website field with your Stamplay domain: https://APP-ID.stamplayapp.com (and/or your custom domain if you have a paid plan).
2.3. Fill in the Authorized Redirect URIs field with the following value: https://APP-ID.stamplayapp.com/auth/v1/twitter/callback. Create the Twitter application.
Add the Twitter Integration to Stamplay
3.1. Click on the Keys and Access Tokens tab.
3.2. Copy the Consumer Key (API Key) and Consumer Secret (API Secret) from the Twitter app and add the values to the Stamplay app.
3.3. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/twitter/connect. Then click on Users in the left menu of the editor to browse the data fetched.
Stamplay collects all profile data provided.
Twitter does not have scopes, and the user email
is not provided. You must request access from Twitter, and be whitelisted to receive user emails.
Please refer to the Twitter documentation for more information.
Dropbox
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/dropbox/connect"
Stamplay.User.socialLogin("dropbox")
// no method
Login a user with a Dropbox account.
Create a Drop API App
1.1. Go to https://www.dropbox.com/developers/apps/create.
1.2. Create a Dropbox API app.
1.3. Choose the values you prefer for the data type and file the app can access (these options are not relevant for login). Name your app.
Configure The Dropbox App
2.1. Fill in the Redirect URIs field in the Oauth2 section with the following value: https://APP-ID.stamplayapp.com (and/or your custom domain if you have a paid plan).
Add the Dropbox Integration To Stamplay
3.1. Copy the App Key and App Secret from the Dropbox app and add the values to the Stamplay app.
3.2. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/dropbox/connect. Then click on “Users” in the left menu of the Editor to browse the data fetched.
3.3. You have added Dropbox login to your Stamplay app, but be aware that you must provide Dropbox with a lot of other information to get their approval. Refer to the Dropbox documentation to learn how to have your Dropbox app approved for production. In the mean time, you can continue to develop and test the integration.
Stamplay collects the following data from Dropbox:
userinfo.profile
Refer to the Dropbox documentation for more information.
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/linkedin/connect"
Stamplay.User.socialLogin("linkedin")
// no method
Login a user with a LinkedIn account.
Create a LinkedIn app
1.1. Go to https://www.linkedin.com/secure/developer and click on “Add a new application”.
Configure the app
2.1. Fill in all the required data.
2.2. Fill in the OAuth redirect_uri field with the following value: https://APP-ID.stamplayapp.com/auth/v1/linkedin/callback.
2.3. Click the “Add application” button.
Add the LinkedIn Integration to Stamplay
3.1. Copy the API Key and Secret Key from the LinkedIn app and add the values to the Stamplay app.
3.2. Click on the “End” button.
3.3. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/linkedin/connect. Then click on Users in the left menu of the Editor to browse the data fetched.
Stamplay asks for the following permissions:
r_basicprofile
r_emailaddress
r_fullprofile
We store only data from r_basicprofile and r_emailaddress
.
Refer to the Linkedin documentation for more information.
Login a user with a Instagram account.
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/instagram/connect"
Stamplay.User.socialLogin("instagram")
// no method
Create an Instagram App
1.1. Go to https://instagram.com/developer/clients/manage.
1.2. Click on Manage Client in the menu bar.
1.3. Click on Register a new Client ID.
Configure the App
2.1. Fill in the required fields.
2.2. Fill in the Website field with your Stamplay domain: https://APP-ID.stamplayapp.com (and/or your custom domain if you have a paid plan).
2.3. Fill in the OAuth redirect_uri field with the following value: https://APP-ID.stamplayapp.com/auth/v1/instagram/callback.
Add the Instagram Integration to Stamplay
3.1. Copy the Client Id and Client Secret from the Instagram client and add the values to the Stamplay app.
3.2. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/instagram/connect. Then click on Users in the left menu of the Editor to browse the data fetched.
Stamplay asks for the following permissions:
basic
We store only data from basic
.
Refer to the Instagram documentation for more information.
Github
Login a user with a Github account.
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/github/connect"
Stamplay.User.socialLogin("github")
// no method
Create a Github App
1.1. Go to https://github.com/settings/profile.
1.2 Click on Applications in the left menu.
1.3. Click on Register new application button.
Configure the app
2.1. Fill in all the required fields.
2.2. Fill in the Homepage URL field with your Stamplay domain: https://APP-ID.stamplayapp.com (and/or your custom domain if you have a paid plan).
2.3. Fill the Authorization Callback URL field with the following value: https://APP-ID.stamplayapp.com/auth/v1/github/callback.
Add the Github Integration to Stamplay
3.1. Copy the Client ID and Client Secret from the Github app and add the values to the Stamplay app.
3.2. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/github/connect. Then click on Users in the left menu of the Editor to browse the data fetched.
Stamplay requests access to public information. We store all public data.
Refer to the Github documentation for more information.
Angellist
Login a user with an Angellist account.
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/angellist/connect"
Stamplay.User.socialLogin("angellist")
// no method
Create an Angel List App
1.1. Go to https://angel.co/api/oauth/clients.
Configure the App
2.1. Name your app.
2.2. Fill in the Main URL field with your Stamplay domain: https://APP-ID.stamplayapp.com (and/or your custom domain if you have a paid plan).
2.3. Fill in the field Callback URL with the following value: https://APP-ID.stamplayapp.com/auth/v1/angellist/callback.
Add the Angellist Integration to Stamplay
3.1. Angel List will send you an email with the Client ID and Client Secret. Add these values to the Stamplay app.
3.2. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/angellist/connect. Then click on Users in the left menu of the Editor to browse the data fetched.
Stamplay requests permission to access the following:
default information
email
We store the default information data and email.
Refer to the Angel List documentation for more information.
Slack
Login a user with a Slack account.
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/slack/connect"
Stamplay.User.socialLogin("slack")
// no method
Create an Slack App
1.1. Go to https://api.slack.com.
Configure the App
2.1. Name your app.
2.2. Fill in the field Redirect URL with the following value: https://APP-ID.stamplayapp.com/auth/v1/slack/callback.
2.3 Click on App Credentials to get your Client Id and Client Secret.
Add the Slack Integration to Stamplay
3.1 Go to Users > Authentication > Slack. Enter your app credentials and click Save.
3.2. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/slack/connect. Then click on Users in the left menu of the Editor to browse the data fetched.
Stamplay requests permission to access the following:
access your team's profile information
We store the default information data and email.
Refer to the Slack API documentation for more information.
Auth0
Login a user with Auth0.
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/auth0/connect"
Stamplay.User.socialLogin("auth0")
// no method
Create an Slack App
1.1. Go to https://manage.auth0.com.
Configure the App
2.1. Go to Client > + New Client.
2.2. Fill in the field Allowed Callback URLs with the following value: https://APP-ID.stamplayapp.com/auth/v1/auth0/callback.
Add the Auth0 Integration to Stamplay
3.1 Go to Users > Authentication > Auth0. Enter your app credentials and click Save.
3.2. To quickly test the integration, copy and paste this link into your browser: https://APP-ID.stamplayapp.com/auth/v1/auth0/connect. Then click on Users in the left menu of the Editor to browse the data fetched.
Stamplay requests permission to access the following:
username
password
We store the default information data and email.
Refer to the Auth0 documentation for more information.
Sessions
"Authorization" : "Basic c3RhbXBsYXlrYjo5MTRhMmUzMaMwZWRlMDdmZThhNjYzMzkxMWQyYWQyOTNkNjJkNTQ3OGFiYmViNjEyNzhhYjFjYzE2MDhiZaRi"
"x-stamplay-jwt" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoidXNlciIsImFwcERvbWFpbiI6InN0YW1wbGF5a2Iuc3RhbXBsYXlscHAuY29tIiwiYXBwSWQiOiJzdGFtcGxheWtiIiwidXNlciI6IjU2ZjAyZDY0NjFkNWI0MTA1ZDFhMjY4NCIsImlhdCI6MTQ1ODU4MTQwNiwiZXhwIjoxNDU5MTg2Mjc4fQ.UDFUe0Zb2ZHx3HXdiUXWnHSyKghVI_harpkkyC3BU8A"
A session represents an instance of a user logged into a device within a Stamplay application. A session is automatically created when users log in or sign up.
By default user sessions last 7 days.
Stamplay manages session leveraging a Token-Based Authentication approach. This relies on a signed token that is sent to the server on each request. The implementation is done by generating a token when the user is authenticated and then setting that token in the x-stamplay-jwt
header of each subsequent request to our back-end, or as part of the Authorization
header from server to server requests.
If you use the Stamplay Javascript SDK you do not need to worry about this; but in the case you send request to our APIs without the SDK, this is something you need to be aware of.
If users log in or sign up using an external provider (e.g. Facebook, Linkedin, Google, etc.) the token issued by Stamplay will be available as a query param ?jwt
. Again, if you are using the SDK, you will not need to manage the token yourself.
If your app let users log in or sign up with the traditional email+password API, tokens will be in the x-stamplay-jwt
header of the response.
To check whether or not the token is expired you can do the following:
- Split the token in three parts using the
.
(dot) as the divider. - Base64 decode of the second chunk.
- Check if the current date (in UNIX timestamp format) is between the "issued at time" date and "expiration" date to check that the token is still valid.
Reset Password
curl -X "POST" "https://stamplaykb.stamplayapp.com/api/user/v1/users/resetpassword" \
-H "Content-Type: application/json" \
-d '{"email":"user@stamplay.com", "newPassword" : "stamplay_rocks!"}'
var emailAndNewPass = {
email: "user@stamplay.com",
newPassword: "stamplay_rocks!"
}
Stamplay.User.resetPassword(emailAndNewPass)
.then(function(res){
// success
}, function(err) {
// error
})
The JSON response looks like.
{
"status": "ok"
}
Reset a local user's account password.
Successful submission of a password reset request will send an email to the account holder's email address with a confirmation link that will set the password reset into affect.
Attribute | Optional | |
---|---|---|
email |
valid email address associated with the account | |
newPassword |
new password for the account being reset |
User to User Permissions
Stamplay supports Role-Based Authorization schemes, on a per object level, and user to user level.
The Roles scheme can be configured with the Users section Roles section for the Role -> Role permissions, and inside each Object model's view under the Permissions tab for each object individual schema.
For further detail, view the Roles documetation.
Logging Out
curl -X "GET" "https://APP-ID.stamplayapp.com/auth/v1/logout" \
-H "x-stamplay-jwt: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoidXNlciIsImFwcERvbWFpbiI6InN0YW1wbGF5a2Iuc3RhbXBsYXlscHAuY29tIiwiYXBwSWQiOiJzdGFtcGxheWtiIiwidXNlciI6IjU2ZjAyZDY0NjFkNWI0MTA1ZDFhMjY4NCIsImlhdCI6MTQ1ODU4MTQwNiwiZXhwIjoxNDU5MTg2Mjc4fQ.UDFUe0Zb2ZHx3HXdiUXWnHSyKghVI_harpkkyC3BU8A"
//sync
Stamplay.User.logout();
//async
Stamplay.User.logout(true, function(err, res){
……
})
// no method
Response is a redirect, as specified in the Authentication section in Stamplay.
To logout and end a user session, send a request to the logout endpoint. The x-stamplay-jwt
header must be included otherwise the session will not be ended.
The request response will redirect the application by default to the root of your application. This can be managed within the Stamplay editor in the User -> Authentication section by select the settings icon.
Fetch Users
Retrieve an individual user, all users, or the current session user, or any users matching specific criteria.
Current User
curl -X "GET" "https://APP-ID.stamplayapp.com/api/user/v1/getstatus" \
-H "x-stamplay-jwt: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoidXNlciIsImFwcERvbWFpbiI6InN0YW1wbGF5a2Iuc3RhbXBsYXlscHAuY29tIiwiYXBwSWQiOiJzdGFtcGxheWtiIiwidXNlciI6IjU2ZjAyZDY0NjFkNWI0MTA1ZDFhMjY4NCIsImlhdCI6MTQ1ODU4MTQwNiwiZXhwIjoxNDU5MTg2Mjc4fQ.UDFUe0Zb2ZHx3HXdiUXWnHSyKghVI_harpkkyC3BU8A"
Stamplay.User.currentUser()
.then(function(res) {
// success
}, function(err) {
// error
})
// no method
The JSON response looks like this.
{
"user":{
"_id":"5685876dcb19408f345a4890",
"email":"isaiahgrey@gmail.com",
"givenRole":"56838ed5948583ff7dcd7c9f",
"appId":"stamplay-angular-seed",
"salt":"875be8da8da96d5a2c16",
"__v":0,
"password":"$2a$12$bAV9Wxl8LmgY.BazFi.o.OsTPrJS9tc2Ih3po6GxGh8SNW0BiIDiq",
"dt_update":"2015-12-31T19:52:13.576Z",
"dt_create":"2015-12-31T19:52:13.576Z",
"emailVerified":true,
"verificationCode":"359472b0e1f115fc5006",
"profileImg":"",
"id":"5685876dcb19408f345a4890"
}
}
To fetch the user that is currently logged in, send a request to the getStatus
endpoint, on the user API resource.
Fetch User By Id
curl -X "GET" "https://APP-ID.stamplayapp.com/api/user/v1/users/:user_id"
Stamplay.User.get({ _id : "user_id" })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.User.get({ _id : "user_id" }, function(err, res) {
// success
})
The JSON response looks like this.
{
"data":[
{
"_id":"5685876dcb19408f345a4890",
"email":"isaiahgrey@gmail.com",
"givenRole":"56838ed5948583ff7dcd7c9f",
"appId":"stamplay-angular-seed",
"salt":"875be8da8da96d5a2c16",
"__v":0,
"password":"$2a$12$bAV9Wxl8LmgY.BazFi.o.OsTPrJS9tc2Ih3po6GxGh8SNW0BiIDiq",
"dt_update":"2015-12-31T19:52:13.576Z",
"dt_create":"2015-12-31T19:52:13.576Z",
"emailVerified":true,
"verificationCode":"359472b0e1f115fc5006",
"profileImg":"",
"id":"5685876dcb19408f345a4890"
}
],
"pagination":{
"page":1,
"per_page":20,
"total_pages":1,
"total_elements":1
}
}
To fetch an single user, send the _id
of the user to fetch in the request body to the user API resource.
Attribute | Optional | |
---|---|---|
user_id |
the Stamplay _id of the user to fetch |
All Users
curl -X "GET" "https://APP-ID.stamplayapp.com/api/user/v1/users"
Stamplay.User.get({})
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.User.get({}, function(err, res) {
// success
})
The JSON response looks like this.
{
"data":[
{
"_id":"568463adcb19408f345a4870",
"givenRole":"56838ed5948583ff7dcd7c9f",
"dt_update":"2015-12-30T23:07:25.730Z",
"dt_create":"2015-12-30T23:07:25.730Z",
"emailVerified":true,
"verificationCode":"c4b0263a8cb5bea890ca",
"profileImg":"",
"id":"568463adcb19408f345a4870"
},
{
"_id":"5685876dcb19408f345a4890",
"givenRole":"56838ed5948583ff7dcd7c9f",
"dt_update":"2015-12-31T19:52:13.576Z",
"dt_create":"2015-12-31T19:52:13.576Z",
"emailVerified":true,
"verificationCode":"c4b0263a8cb5bea890ca",
"profileImg":"",
"id":"5685876dcb19408f345a4890"
},
...
...18 More
...
],
"pagination":{
"page":1,
"per_page":20,
"total_pages":1,
"total_elements":19
}
}
To retrieve all users, send a request without any parameters to match in the body, to the user API resource.
Query Users
curl -X "GET" "https://APP-ID.stamplayapp.com/api/user/v1/users" \
-H "Content-Type: application/json" \
-d "{\"name\":\"John\",\"age\":\"30\"}"
var query = {
name : "John",
age : 30
}
Stamplay.User.get(query)
.then(function(res) {
// success
}, function(err) {
// error
})
var query = {
name : "John",
age : 30
}
Stamplay.User.get(query, function(err, res) {
// success
})
The JSON response looks like this.
{
"data":[
{
"_id":"568463adcb19408f345a4870",
"name" : "John",
"age" : 30,
"givenRole":"56838ed5948583ff7dcd7c9f",
"dt_update":"2015-12-30T23:07:25.730Z",
"dt_create":"2015-12-30T23:07:25.730Z",
"emailVerified":true,
"verificationCode":"c4b0263a8cb5bea890ca",
"profileImg":"",
"id":"568463adcb19408f345a4870"
}
],
"pagination":{
"page":1,
"per_page":20,
"total_pages":1,
"total_elements":1
}
}
To retrieve all users that match a certain set of parameters, send a request with any parameters to match in the body, to the user API resource.
Update User
curl -X "PUT" "https://APP-ID.stamplayapp.com/api/user/v1/users/:user_id" \
-H "Content-Type: application/json" \
-d "{\"name\":\"John\",\"age\":\"30\"}"
var updatedInfo = {
name : "John",
age : 30
}
Stamplay.User.update("user_id", updatedInfo)
.then(function(res) {
// success
}, function(err) {
// error
})
var updatedInfo = {
name : "John",
age : 30
}
Stamplay.User.update("user_id", updatedInfo, function(err, res) {
// success
})
The JSON response looks like this.
{
"_id":"570eab5bc0d4b16b26a4bbdc",
"displayName":"",
"givenRole":"57059a25d229692c639df406",
"age":30,
"name":"John",
"dt_update":"2016-04-13T23:16:30.366Z",
"dt_create":"2016-04-13T20:26:03.677Z",
"emailVerified":true,
"verificationCode":"6f11f44ad0ec8bd0fa27",
"profileImg":"",
"id":"570eab5bc0d4b16b26a4bbdc"
}
To update a user record, send a PUT
request with a with updated data.
Include this data in the request body, in the request to the User API resource with the _id
of the user to update.
Attribute | Optional | |
---|---|---|
user_id |
the Stamplay _id of the user to update |
Remove User
curl -X "DELETE" "https://APP-ID.stamplayapp.com/api/user/v1/users/:user_id"
Stamplay.User.remove("user_id")
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.User.remove("user_id", function(err, res) {
// success
})
The JSON response looks like this.
{
"_id":"570eab5bc0d4b16b26a4bbdc",
"displayName":"John",
"givenRole":"57059a25d229692c639df406",
"age":30,
"name":"John",
"dt_update":"2016-04-13T23:16:30.366Z",
"dt_create":"2016-04-13T20:26:03.677Z",
"emailVerified":true,
"verificationCode":"6f11f44ad0ec8bd0fa27",
"profileImg":"",
"id":"570eab5bc0d4b16b26a4bbdc"
}
To remove a user record from the database, send a DELETE
request to the user resource with the user _id
to the User API resource.
Attribute | Optional | |
---|---|---|
user_id |
the Stamplay _id of the user to delete |
Roles
Stamplay supports role based access control for a fine grained authorization layer.
How Roles Work
Roles provide a logical way of grouping users with common access privileges.
Any permission granted to a role is implicitly granted to its users and to the users in any roles it contains.
By default, any Stamplay app has two pre-defined roles: guest
and registered
.
You can add as many roles as you need and define hierarchies to grant a user with role X
the permission to change the role of another user with role Y
.
Roles and permissions each has are defined within the Stamplay editor entirely, the API resource if for reading and assiging the roles you define only.
Fetch All Roles
curl -X "GET" "https://APP-ID.stamplayapp.com/api/user/v1/roles"
Stamplay.User.getRoles()
.then(function(res) {
// success
}, function(err) {
// error
})
// no method
The JSON response looks like this.
{
"data": [
{
"_id": "561c001ce57bdca90ee4482a",
"name": "guest"
},
{
"_id": "561c001ce57bdca90ee4482b",
"name": "registered"
},
{
"_id": "56f8d353e252697a51cce376",
"name": "admin"
}
],
"pagination": {
"page": 1,
"per_page": 20,
"total_elements": 3,
"total_pages": 1
}
}
To retrieve all roles within your application, send a GET
request to the Roles API resource.
Fetch Individual Role
curl -X "GET" "https://APP-ID.stamplayapp.com/api/user/v1/roles/:role_id"
Stamplay.User.getRole("role_Id")
.then(function(res) {
// success
}, function(err) {
// error
})
// no method
The JSON response looks like this.
{
"_id" : "56f8d353e252697a51cce376",
"name" : "admin"
}
To fetch a single role, send a GET
request to the Roles API resource, with the _id
as part of the request URI.
Attribute | Optional | |
---|---|---|
role_id |
the Stamplay _id of the role to fetch |
Assign Role
curl -X "PATCH" "https://APP-ID.stamplayapp.com/api/user/v1/users/:user_id/role" \
-H "Content-Type: application/json" \
-d "{\"givenRole\":\"role_id\"}"
Stamplay.User.setRole("userId", "role_id")
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.User.patch("user_id", { givenRole : "role_id" }, function(err, res) {
// success
})
{
"_id":"570eb000c0d4b16b26a4bbdd",
"email":"user@stamplay.com",
"password":"$2a$12$lv9lbkAiwyvfT13oosMefuWHCp87NC/azMlwYwxsSUVVpw.YI0ZfO",
"givenRole":"570ec91fb7581ccd707c4d48",
"appId":"stamplaykb",
"__v":0,
"username":"",
"displayName":"",
"dt_update":"2016-04-13T22:33:54.595Z",
"dt_create":"2016-04-13T20:45:52.498Z",
"emailVerified":true,
"verificationCode":"65d1b991bd0010536416",
"profileImg":"",
"id":"570eb000c0d4b16b26a4bbdd"
}
To assign a new role to a user, send a PATCH
request with the givenRole
property as the unique _id
of the role to assign in the request body, to the User API resource with the user's _id
as part of the URI.
Attribute | Optional | |
---|---|---|
user_id |
the Stamplay _id of the user to assign a role |
|
role_id |
the Stamplay _id of the role to assign to the user |
Objects
The Object API resource is based of the user defined Schemas in the Stamplay Editor.
For each Schema, and API endpoint is generated, and new database collection is added.
Out of the box, the Object API resource supports user relationships, object relationships, geolocation data, file uploads, and role based interaction for each schema type.
Schemas
Schemas are defined data structures that enfore type validation.
They can be created throught Stamplay Editor, inside the Object section.
Below is an example schema of a Restaurant with every possible data type available as a field type.
There are 3 properties that are included by default:
Attribute | |
---|---|
dt_create |
The date the record was created |
dt_update |
The date the record was last updated |
owner |
The _id of the user who created this object. |
Data Types
The types and formats of each field type is listed below:
In the example schema object below, each key-value pair is a possible schema property type, and a valid value for that property type.
{
"boolean" : true,
"string" : "Hello World",
"number" : 45,
"float" : 3.14,
"plain_object" : {
"prop_one" : "GoodBye World",
"prop_two" : 1200
},
"array_number" : [23, 76, 345],
"array_string" : ["Hello", "World"],
"date" : "2016-03-10T14:51:28.625Z",
"file" : "https://file-upload.stamplayapp.com/upload/cobject/image/1458238116389_file-upload.png",
"_geolocation" : {
"type" : "Point",
"coordinates ": [
12.4608,
41.9015
]
},
"object_relation_array" : [ "562c45af4c0f20367d7ca4be", "562ec06e77589e2e0f86c207"],
"user_relation_string" : "562bb24e007983c67c8ee9df"
}
Type | Summary |
---|---|
Boolean | A boolean value type |
String | String value type. Strings are stored as UTF-8. |
Number | An integer value type. |
Float | A float value type. |
Plain Object | A Javascript object. |
Array - Number | An array of integer value types. |
Array - String | An array of string value types. |
Date | Date value type. Dates are stored in ISODateTimeFormat. |
File | Any kind of file. Location of the resource uploaded. |
Geolocation | GeoJSON object. |
Object Relation - Array | An arrays of pointers to an specific object type. |
User Relation - String | A pointer to a user object. |
Boolean
{
_id: "56cf08e362641ca813b1ae6c",
verified : true
}
A Boolean type is a true
or false
value.
String
{
_id: "56cf08e362641ca813b1ae6c",
name : "John"
}
A String type is a series of characters enclosed by single, or double quotes.
Number
{
_id: "56cf08e362641ca813b1ae6c",
age : 29
}
A Number type is an integer value type without a period or exponent notation.
Float
{
_id: "56cf08e362641ca813b1ae6c",
pie : 3.14
}
A Float type is an integer value type with a period or exponent notation.
Plain Object
{
_id: "56cf08e362641ca813b1ae6c",
car : {
color : "blue",
year : 2014,
automatic : false
}
}
A Plain Object type is a plain javascript object. The property car
is a plain object type in the example.
Array - Number
{
_id: "56cf08e362641ca813b1ae6c",
colors : [12, 43, 235, 66]
}
An Array of Number value types:
Array - String
{
_id: "56cf08e362641ca813b1ae6c",
colors : ["yellow", "green", "blue", "red"]
}
An Array of String value types:
Date
{
_id : "56cf08e362641ca813b1ae6c",
start_date : "2016-03-10T14:51:28.625Z"
}
{
_id : "56cf08e362641ca813b1ae6c",
end_date : "Thu, 10 Mar 2016 14:51:43 GMT"
}
A Date type is a date string in either the ISO 8601 format, or RFC-1123 format.
The property start_date
is a Date type in ISO 8601 format in the first example.
The property end_date
is a Date type in RFC-1123 format in the last example.
File
{
_id : "56cf08e362641ca813b1ae6c",
profile_image : "https://APP-ID.stamplayapp.com/upload/cobject/[cobject-name]/1457032441927_stamplay.png"
}
A File type is a file upload. Any kind of file is accepted. When a file is uploaded, and saved, the property will be a link to the file upload location.
To save a file type, the request must be sent as multipart/form-data
.
The profile_image
is an example of a File type in the example.
Geolocation
{
_id: "56cf08e362641ca813b1ae6c",
_geolocation : {
type: "Point",
coordinates: [
12.4608,
41.9015
]
}
}
A Geolocation type is stored as GeoJSON object with this coordinate-axis order: longitude
, latitude
.
A Point stored on Stamplay will look like the example:
Currently supported data types are:
In order to save any instance of geolocation data you need to send the complete GeoJSON representation.
To make this easier if you want to create a Point you're allowed to send an array of coordinates in longitude, latitude
format and Stamplay will create the GeoJSON for you.
Object Relation
{
_id : "56cf08e362641ca813b1ae6c",
solutions : ["6c641c8a81e3625f03b1ae6c", "3b1ae6c8a81e3625f06c641c", "825f06c641c3ba81e361ae6c", "f06c641c3b8a81e3625ae6c"]
}
A Object Relation is set of pointers to another object.
Select the Object Relation - [Object Name] from the dropdown to the object type to point to. The pointers are each a _id
of another object. This field can be populated.
The solutions
property is an example of a Object Relation type in the example.
User Relation
{
_id : "56cf08e362641ca813b1ae6c",
author : "8a81e3625f06c641c3b1ae6c"
}
A User Relation is a pointer to a user object represented by an _id
of a user. This field can be populated. The author
property is an example of a User Relation
in the example.
Permissions
With permissions at an Object level, you define who can perform operations on your data. You can do that by choosing a preset or creating your own permission model.
We’ve identified some commonly used permission patterns (we refer to them as "policies"). Stamplay provides an easy way to use these patterns on the data your app manages. These policies offer a convenient mechanism for supporting very common security scenarios without having to manage complex settings:
-
Private: Use this preset if you want to make users’ data inaccessible to other users. Any user will be able to read and write only his or her own information.
-
Public: When this policy is applied to user profiles, any user can read and write any other user's information. Proceed with caution.
-
Read-only: Use this preset if you want users to read all profiles, but you don’t want to give them permission to write any profile information.
-
Shared: This preset is suitable for social apps; any user can modify his or her own profile and can read all other user profiles.
If the predefined security policies are not flexible enough for your app and you have created your own user roles, you can choose to use role-based security. The settings specify whether a role is allowed to create, read, update or delete items.
Create
curl -X "POST" "https://APP-ID.stamplayapp.com/api/cobject/v1/object" \
-H "Content-Type: application/json" \
-d "{\"title\":\"\\\"Hello World\\\"\",\"year\":\"2016\"}"
var data = {
title : "Hello World",
year : 2016
}
Stamplay.Object("movie").save(data)
.then(function(res) {
// success
}, function(err) {
// error
})
var data = {
title : "Hello World",
year : 2016
}
Stamplay.Object("movie").save(data, function(err, res) {
// response
})
The JSON response looks like this.
{
"__v":0,
"title":"Hello World",
"year":2016,
"appId":"stamplay-docs",
"cobjectId":"movie",
"_id":"570edb76fc24091627e82086",
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"id":"570edb76fc24091627e82086"
}
To create new object data for a particular model, send the data in the body of aPOST
request to the Object resource, specifying the object type in the URI.
Fetch Objects
Retrieve an individual object, all objects, or any matching specific criteria of a particular model type.
Fetch Object By Id
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie/:object_id"
Stamplay.Object("movie").get({ _id : "object_id"})
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object("movie").get({ _id : "object_id"}, function(err, res) {
// response
})
The JSON response looks like this.
{
"data":[
{
"_id":"570edb76fc24091627e82086",
"title":"Hello World",
"year":2016,
"appId":"stamplay-docs",
"cobjectId":"movie",
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"__v":0,
"id":"570edb76fc24091627e82086"
}
],
"pagination":{
"page":1,
"per_page":20,
"total_pages":1,
"total_elements":1
}
}
To fetch a single object, send a GET
request to the Object resource with the object's _id
in the URI.
The object type for the example is movie
.
Attribute | Optional | |
---|---|---|
object_id |
the Stamplay _id of the object to retrieve |
All Objects
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie"
Stamplay.Object("movie").get({})
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object("movie").get({}, function(err, res) {
// response
})
The JSON response looks like this.
{
"data":[
{
"_id":"570edb76fc24091627e82086",
"title":"Hello World",
"year":2016,
"appId":"stamplay-docs",
"cobjectId":"movie",
"actions":{ ... },
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"__v":0,
"id":"570edb76fc24091627e82086"
},
{
"_id":"570edcc7fc24091627e82087",
"title":"Goodbye World",
"year":2014,
"appId":"stamplay-docs",
"cobjectId":"movie",
"actions":{ ... },
"dt_update":"2016-04-13T23:56:55.060Z",
"dt_create":"2016-04-13T23:56:55.060Z",
"__v":0,
"id":"570edcc7fc24091627e82087"
}
...
...12 more
...
],
"pagination":{
"page":1,
"per_page":20,
"total_pages":1,
"total_elements":14
}
}
To fetch all objects, send a GET
request to the Object resource.
The object type for the example is movie
.
Query Objects
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie?year=1998"
var query = {
year : 1998
}
Stamplay.Object("movie").get(query)
.then(function(res) {
// success
}, function(err) {
// error
})
var query = {
year : 1998
}
Stamplay.Object("movie").get(query, function(err, res) {
// response
})
The JSON response looks like this.
{
"data":[
{
"_id":"570edb76fc24091627e82086",
"title":"Goodbye 90's",
"year":1998,
"appId":"stamplay-docs",
"cobjectId":"movie",
"actions":{ ... },
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"__v":0,
"id":"570edb76fc24091627e82086"
},
{
"_id":"570edcc7fc24091627e82087",
"title":"Again not again.",
"year":1998,
"appId":"stamplay-docs",
"cobjectId":"movie",
"actions":{ ... },
"dt_update":"2016-04-13T23:56:55.060Z",
"dt_create":"2016-04-13T23:56:55.060Z",
"__v":0,
"id":"570edcc7fc24091627e82087"
}
],
"pagination":{
"page":1,
"per_page":20,
"total_pages":1,
"total_elements":2
}
}
To fetch all objects that match a certain parameters, send a GET
request to the Object resource with any parameters to match in the request body.
For more advanced queries, visit the Advanced Queries section for more information.
The object type for the example is movie
.
Find By Current User
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie/find/director"
// default attribute is owner is no arguments are passed to method
Stamplay.Object("movie").findByCurrentUser('director')
.then(function(res) {
// Success
}, function(err) {
// Error
}))
// no method
The JSON response looks like this.
{
"data":[
{
"_id":"570edb76fc24091627e82086",
"title":"Hello World",
"year":2016,
"director" : "5503de76fc24091627e82568",
"appId":"stamplay-docs",
"cobjectId":"movie",
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"__v":0,
"id":"570edb76fc24091627e82086"
},
{
"_id":"570edcc7fc24091627e82087",
"title":"Goodbye World",
"year":2014,
"director" : "5503de76fc24091627e82568",
"appId":"stamplay-docs",
"cobjectId":"movie",
"dt_update":"2016-04-13T23:56:55.060Z",
"dt_create":"2016-04-13T23:56:55.060Z",
"__v":0,
"id":"570edcc7fc24091627e82087"
}
],
"pagination":{
"page":1,
"per_page":20,
"total_pages":1,
"total_elements":2
}
}
To find any records whose field value is equal to the current user's _id
, you can use the find by owner resource to simplify querying through different fields.
Make a GET
request to the Object resource for the object model. Specifying the attribute in the resource URI.
The object type for the example is movie
.
Update Objects
To update an object record partially, or completely overwrite the existing record.
Partial Update
curl -X "PATCH" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie/:object_id" \
-H "Content-Type: application/json" \
-d "{\"title\":\"Goodbye World\"}"
var data = {
"title" : "Goodbye World"
}
Stamplay.Object("movie").patch("object_id", data)
.then(function(res) {
// success
}, function(err) {
// error
})
var data = {
"title" : "Goodbye World"
}
Stamplay.Object("movie").patch("object_id", data, function(err, res) {
// response
})
The JSON response looks like this.
{
"_id":"570edb76fc24091627e82086",
"title": "Goodbye World",
"year":2016,
"director" : "5503de76fc24091627e82568",
"appId":"stamplay-docs",
"cobjectId":"movie",
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"__v":0,
"id":"570edb76fc24091627e82086"
}
To make a partial update to an object record, perform a PATCH
request to the Object API resource with any fields to update on the stored record in the request body.
Attribute | Optional | |
---|---|---|
object_id |
the Stamplay _id of the object to update |
The object type for the example is movie
.
Complete Update
curl -X "PUT" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie/:object_id" \
-H "Content-Type: application/json" \
-d "{\"title\":\"Goodbye World\",\"year\":\"2001\"}"
var data = {
"title" : "Goodbye World"
}
Stamplay.Object("movie").update("object_id", data)
.then(function(res) {
// success
}, function(err) {
// error
})
var data = {
"title" : "Goodbye World"
}
Stamplay.Object("movie").update("object_id", data, function(err, res) {
// response
})
The JSON response looks like this.
{
"_id":"570edb76fc24091627e82086",
"title": "Goodbye World",
"year":2016,
"director" : "5503de76fc24091627e82568",
"appId":"stamplay-docs",
"cobjectId":"movie",
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"__v":0,
"id":"570edb76fc24091627e82086"
}
To overwrite an object record, perform a PUT
request to the Object API resource with a complete represenation to write over the stored record in the request body.
Attribute | Optional | |
---|---|---|
object_id |
the Stamplay _id of the object to update |
Remove Objects
To remove an object record, send a DELETE
request with the _id
of the record to remove in the Object API resource URI.
curl -X "DELETE" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie/:object_id"
Stamplay.Object("movie").remove("object_id")
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object("movie").remove("object_id", function(err, res) {
// response
})
The JSON response will look like this.
{
"_id":"570edb76fc24091627e82086",
"title":"Hello World",
"year":2016,
"appId":"stamplay-docs",
"cobjectId":"movie",
"__v":0,
"dt_update":"2016-04-13T23:51:18.170Z",
"dt_create":"2016-04-13T23:51:18.170Z",
"id":"570edb76fc24091627e82086"
}
Attribute | Optional | |
---|---|---|
object_id |
the Stamplay _id of the object to remove |
Relationships
Data relationships are pointers from one record to another.
User Relationship
curl -X "PATCH" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie/:object_id" \
-H "Content-Type: application/json" \
-d "{\"director\":\"56cf08e362641ca813b1ae6c\"}"
Stamplay.Object("movie").patch("object_id", { director: "56cf08e362641ca813b1ae6c" })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object("movie").patch("object_id", { director: "56cf08e362641ca813b1ae6c" }, function(err, res) {
// response
})
A User relationship is a pointer to a user record. This field type is to be set only as an _id
of a user record.
This is so it may be populated with the parent object, eliminating the need for a subsequent request to fetch the relationship data. To populate the owner
field, include the query parameter populate_owner
as true
in your request.
The owner
property is a default User relationship field on an Object record.
When using the SDK, this field is set if a current user session is in progress, otherwise it is left blank. To add owner's to your Object records when using the REST API or Node.js SDK, set this field as the owner of the record.
To manage these relationships, just update this field to the "_id" of the User to reference in the relationship.
Attribute | Optional | |
---|---|---|
object_id |
the Stamplay _id of the object to update |
In this example, movie
is the object type, and the director
field is a User Relationship field.
Object Relationships
curl -X "PATCH" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie/:object_id" \
-H "Content-Type: application/json" \
-d "{\"characters\":[\"57cf08e362641ca813b1ae6c\",\"56cf09e362641sa813b1ae6d\",\"54cfdae662641ca813b1ae6c\"]}"
Stamplay.Object("movie").push("object_id", "characters", "57cf08e362641ca813b1ae6c")
.then(function(res) {
// success
}, function(err) {
// error
})
var movieChars = ["57cf08e362641ca813b1ae6c", "56cf09e362641sa813b1ae6d", "54cfdae662641ca813b1ae6c"]
Stamplay.Object("movie").patch("object_id", movieChars, function(err, res) {
// response
})
An Object relationship is a pointer to another record; specifically a certain type of record as specified when defining the schema.
This field type is to contain only an array of the property _id
of a each related record of the relationship type.
This is so it may be populated with the parent object, eliminating the need for a subsequent request to fetch the relationship data. To populate these fields, add the query parameter populate
as true
to your request.
To manage this relationship field, update the field to represent the collection of object references to store.
The JavaScript SDK has a push
method to allow an easier method for pushing new relationships onto the array field. See the example in the JavaScript
tab, otherwise you will need to manage this manually by sending a complete copy of the field in the request.
Attribute | Optional | |
---|---|---|
object_id |
the Stamplay _id of the object to add a relationship to |
In this example, movie
is the object type, and the characters
field is a Object Relationship field.
Retrieving Related Records
To retrieve related records, use the populate
parameter in any GET
request, and any populable fields will be filled with their respective objects in place of their _id
.
curl -X "GET" "https://APP-ID.stamplayapp.com/api/cobject/v1/movie?populate=true"
Stamplay.Object("movie").get({ populate : true })
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Object("movie").get({ populate : true }, function(err, res) {
// response
})
Files
curl -X "POST" \
-F 'image=@/path/to/pictures/picture.jpg' \
-F 'title=Lord of the Rings' \
"https://APP-ID.stamplayapp.com/api/cobject/v1/movie"
var url = 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie';
var input = document.getElementById('file-upload');
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
method : 'POST'
url: url,
data: fd,
contentType: false,
processData: false,
success : function(response){
console.log(response);
},
error : function(err){
console.log(err.responseText);
}
});
const request = require('request');
const fs = require('fs');
const path = require('path');
var formData = {
image: fs.createReadStream(path.join(__dirname, 'picture.jpg')),
};
request.post({
url: 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie',
formData: formData
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
if (httpResponse.statusCode != 200) {
return console.error('upload failed', body)
}
console.log('Upload successful! Server responded with:', body);
});
Stamplay objects support file upload as a property type. This let you attach any file to an object record via API. There are no file type restrictions but maximum upload size is 10 MB.
To save an object containing a file type, the request must have content-type multipart/form-data
, note that you can send in the same API call other properties that are not a file.
Advanced Queries
In some cases, retrieving objects by an _id
or by simple filter methods aren't powerful enough to specify which objects you want to retrieve from the back-end.
Queries offer a different way to retrieve a list of objects, or users.
Introduction
Advanced query methods use a where
parameter set to a JSON query string.
The Stamplay.Query
class uses use a where
url parameter set to a JSON query string under the hood.
?where={ field : { $query_operator : field_value }
// Querying Users
`Stamplay.Query("user", "users").someQueryMethod()`
// Querying Objects
`Stamplay.Query("object", "cobject_id").someQueryMethod()`
// Querying Users
`Stamplay.Query("user", "users").someQueryMethod()`
// Querying Objects
`Stamplay.Query("object", "cobject_id").someQueryMethod()`
The advanced filter methods used are just MongoDB query operators, that Stamplay allow's to be set inside query string on the client side.
The exhaustive list of MongoDB operators available can be found in the API Overview Section under Advanced Queries.
Comparing Values
When filtering through certain field types, we often need the ability to check if a value falls within a certain range, versus strictly matching.
This often applies to integer value type fields where one might want to return all records where a value is greater than one value but less than or equal to another.
Another scenario, within date fields. We can use the same comparator expressions to see if a date value if before or after, or on another.
When querying a date field, pass in an data ISO
string as the value to compare against, or unix timestamp.
The following methods are useful for doing such comparisons within a query:
Method | |
---|---|
greaterThan |
check if a value is greater than a given value |
greaterThanOrEqual |
check if a value is less than a given value |
lessThan |
check if a value is greater than a given value or equal to |
lessThanOrEqual |
check if a value is less than a given value or equal to |
The following operators are useful for doing such comparisons within a query:
Operator | |
---|---|
$gt |
check if a value is greater than a given value |
$gte |
check if a value is less than a given value |
$lt |
check if a value is greater than a given value or equal to |
$lte |
check if a value is less than a given value or equal to |
Greater Than
To retrieve all records where an integer specified is greater than another, or where a date is after another date, use the $gt
mongo operator.
To retrieve all records where an integer specified is greater than another, or where a date is after another date, use the greaterThan
SDK method.
// returns records where the rating is greater than 4
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"actions.ratings.total":\{"$gt":4\}\}'
// returns records that were created after January 15, 2015
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"dt_create":\{"$gt":"2015-01-15T08:00:00.000Z"\}\}'
// returns records where the rating is greater than 4
Stamplay.Query('object','movie')
.greaterThan('actions.ratings.total', 4)
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records that were created after January 15, 2015
Stamplay.Query('object','movie')
.greaterThan('dt_create', "2015-01-15T08:00:00.000Z")
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records where the rating is greater than 4
Stamplay.Query('object','movie')
.greaterThan('actions.ratings.total', 4)
.exec(function(err, res){
// response
})
// returns records that were created after January 15, 2015
Stamplay.Query('object','movie')
.greaterThan('dt_create', "2015-01-15T08:00:00.000Z")
.exec(function(err, res){
// response
})
Greater Than Or Equal To
To retrieve all records where an integer specified is greater than or equal to another, or where a date is on or after another date, use the $gte
mongo operator.
To retrieve all records where an integer specified is greater than or equal to another, or where a date is on or after another date, use the greaterThanOrEqual
SDK method.
// returns records with a rating of 4 or greater
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"actions.ratings.total":\{"$gte":4\}\}'
// returns records that were last updated on or after April 11, 2012
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"dt_update":\{"$gte":"2012-04-11T07:00:00.000Z"\}\}'
// returns records with a rating of 4 or greater
Stamplay.Query('object','movie')
.greaterThanOrEqual('actions.ratings.total', 4)
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records that were last updated on or after April 11, 2012
Stamplay.Query('object','movie')
.greaterThanOrEqual('dt_update', "2012-04-11T07:00:00.000Z")
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records with a rating of 4 or greater
Stamplay.Query('object','movie')
.greaterThanOrEqual('actions.ratings.total', 4)
.exec(function(err, res){
// response
})
// returns records that were last updated on or after April 11, 2012
Stamplay.Query('object','movie')
.greaterThanOrEqual('dt_update', "2012-04-11T07:00:00.000Z")
.exec(function(err, res){
// response
})
Less Than
To retrieve all records where an integer specified is less than another, or where a date is before another date, use the $lt
mongo operator.
To retrieve all records where an integer specified is less than another, or where a date is before another date, use the lessThan
SDK method.
// returns records with a rating of less than 4
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"actions.ratings.total":\{"$lt":4\}\}'
// returns records that were created before January 15, 2015
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"dt_create":\{"$lt":"2015-01-15T08:00:00.000Z\}\}'
// returns records with a rating of less than 4
Stamplay.Query('object','movie')
.lessThan('actions.ratings.total', 4)
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records that were created before January 15, 2015
Stamplay.Query('object','movie')
.lessThan('actions.ratings.total', 4)
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records with a rating of less than 4
Stamplay.Query('object','movie')
.lessThan('actions.ratings.total', 4)
.exec(function(err, res){
// response
})
// returns records that were created before January 15, 2015
Stamplay.Query('object','movie')
.lessThan('actions.ratings.total', 4)
.exec(function(err, res){
// response
})
Less Than Or Equal To
To retrieve all records where an integer specified is less than or equal to another, or where a date is on or before another date, use the $lte
mongo operator.
To retrieve all records where an integer specified is less than or equal to another, or where a date is on or before another date, use the lessThanOrEqual
SDK method.
// returns records with a rating of 4 or less
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"actions.ratings.total":\{"$lte":4\}\}'
// returns records that were last updated on or before April 11, 2012
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"dt_update":\{"$lte":"2012-04-11T07:00:00.000Z"\}\}'
// returns records with a rating of 4 or less
Stamplay.Query('object','movie')
.lessThanOrEqual('actions.ratings.total', 4)
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records that were last updated on or before April 11, 2012
Stamplay.Query('object','movie')
.lessThanOrEqual('dt_update', "2012-04-11T07:00:00.000Z")
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// returns records with a rating of 4 or les
Stamplay.Query('object','movie')
.lessThanOrEqual('actions.ratings.total', 4)
.exec(function(err, res){
// response
})
// returns records that were last updated on or before April 11, 2012
Stamplay.Query('object','movie')
.lessThanOrEqual('dt_update', "2012-04-11T07:00:00.000Z")
.exec(function(err, res){
// response
})
Selection and Sorting
Stamplay provides an easy to use interface for selecing what data from an object is returned, and in what order the records are returned.
Selecting Return Fields
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?select=title,actions.ratings.total'
Stamplay.Query("object", "cobject_id")
.select("title", "actions.ratings.total")
.exec()
.then(function() {
// success
}, function(err) {
// error
})
Stamplay.Query("object", "cobject_id")
.select("title", "actions.ratings.total")
.exec()
.then(function() {
// success
}, function(err) {
// error
})
To select fields of return for query, add the select
query parameter the request URI, and add the attributes to return as a comma delimited list assigned to select
.
To return only certain properties of a field, set them as a dot notated attribute in the comma delimited list. In the example actions.ratings.total
, is set a return field.
The object structure is maintained, however any other properties not specified will not be returned.
To select fields of return for query, use the select
query method on the Stamplay.Query
, and add the attributes to return as method arguments.
To return only certain properties of a field, pass them in as a dot notated attribute as seen in the example with actions.ratings.total
.
Sorting Query Results
// sort by title - ascending order
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?sort=title'
// sort by title by descending order (note the hyphen preceding the sort param value)
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?sort=-title'
// sort by title in ascending order
Stamplay.Query("object", "cobject_id")
.sortAscending("title")
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// sort by title in descending order
Stamplay.Query("object", "cobject_id")
.sortDescending("title")
.exec()
.then(function() {
// success
}, function(err) {
// error
})
// sort by title in ascending order
Stamplay.Query("object", "cobject_id")
.sortAscending("title")
.exec()
.exec(function(err, res){
if(err) return console.log(err);
console.log(res);
})
// sort by title in descending order
Stamplay.Query("object", "cobject_id")
.sortDescending("title")
.exec(function(err, res){
if(err) return console.log(err);
console.log(res);
})
By default, Stamplay returns results in ascending order of the dt_create
property, or the date created.
To change the order in which the records are sorted in the response, pass in a sort
parameter and set the value as the attribute to sort by. An attribute preceded by an -
(hyphen) is sorted in descending order.
To change the order in which the records are sorted in the response, call the sortAscending
or sortDescending
method on your query, and pass in the attribute to sort by.
Regular Expressions
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"title":\{"$regex":"^Star","$options":"i"\}\}'
Stamplay.Query('object','question')
.regex('title','^Star', 'i')
.exec()
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Query('object','question')
.regex('title','^Star', 'i')
.exec(function(err, res){
// response
})
Regular Expressions allow pattern matching for strings in queries. For a full list of options available, and more on pattern matching see the MongoDB Documentation on $regex.
The example returns records where the title
starts with Star
, with option i
(disables case sensitivity).
Compound Queries
curl -X "GET" 'https://stamplaykb.stamplayapp.com/api/cobject/v1/question?where=\{"$or":\[\{"actions.rating.total":\{"$gt":4\}\},\{"title":"Star Wars"\}\]\}'
var ratedFourOrMore = Stamplay.Query("object", "movie");
var titleIsStarWars = Stamplay.Query("object", "movie");
ratedFourOrMore.greaterThanOrEqual("actions.ratings.total", 4);
titleIsStarWars.equalTo("title", "Star Wars");
var combinedQuery = Stamplay.Query("object", "movie");
combinedQuery.or(ratedFourOrMore, titleIsStarWars);
combinedQuery.exec()
.then(function(res) {
// success
}, function(err) {
// error
})
var ratedFourOrMore = Stamplay.Query("object", "movie");
var titleIsStarWars = Stamplay.Query("object", "movie");
ratedFourOrMore.greaterThanOrEqual("actions.ratings.total", 4);
titleIsStarWars.equalTo("title", "Star Wars");
var combinedQuery = Stamplay.Query("object", "movie");
combinedQuery.or(ratedFourOrMore, titleIsStarWars);
combinedQuery.exec(function(err, res) {
// response
})
When performing a query, you might want to find records that match one of two or more sets of criteria, instead of a strict match for each attribute.
Being able to make compound queries eliminates making several requests, simplifying application development.
To build a compound query, use the $or
operator, and set an array of regular query objects. Any records matching at least one of the criteria objects will be returned.
To build a compound query, use the or()
method, and pass in the query objects are arguments. Any records matching at least one of the criteria objects will be returned.
Geolocation Queries
Geolocation queries allow you to find records whose geo data match a set of geo parameters specified in the query.
Stamplay supports the follow MongoDB operators for querying geolocation data:
Operator | |
---|---|
$geoWithin |
Returns records within the bounds GeoJSON geometry. |
$geoIntersects |
Returns records that intersect with a GeoJSON geometry |
$near |
Return records within a specified proximity to a point |
$nearSphere |
Return records within a specified proximity to a point on a sphere |
The following SDK methods are available for querying geolocation data:
Method | |
---|---|
geoWithinGeometry |
Returns records within a geometric boundary. |
geoIntersects |
Returns records that intersect with a GeoJSON geometry |
near |
Return records within a specified proximity to a point |
nearSphere |
Return records within a specified proximity to a point on a sphere |
Within a Geometric Boundary
curl -X "GET" 'https://APP-ID.stamplayapp.com/api/cobject/v1/movie?where=\{"_geolocation":\{"$geoWithin":\{"$geometry":\{"type":"Polygon","coordinates":\[\[\[-70,40\],\[-72,40\],\[-72,50\],\[-70,50\],\[-70,40\]\]\]\}\}\}\}'
Stamplay.Query("object", "movie")
.geoWithinGeometry('Polygon',
[
[ [-70,40], [-72,40], [-72,50], [-70, 50], [-70, 40] ]
]).exec()
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Query("object", "movie")
.geoWithinGeometry('Polygon',
[
[ [-70,40], [-72,40], [-72,50], [-70, 50], [-70, 40] ]
]).exec(function(err,res) {
// response
})
Find and return records that are within a specified polygon.
The $geoWithin
MongoDB operator accepts a GeoJSON Polygon or a MultiPolygon.
The geoWithinGeometry
SDK method accepts a GeoJSON Polygon or a MultiPolygon.
For more information about finding records within a geometric boundray, see the MongoDB documention for $geoWithin.
Intersects a Geometric Boundary
curl -X "GET" 'https://stamplaykb.stamplayapp.com/api/cobject/v1/question?where=\{"_geolocation":\{"$geoIntersects":\{"$geometry":\{"type":"Point","coordinates":\[74.0059,40.7127\]\}\}\}\}'
Stamplay.Query("object", "movie")
.geoIntersects('Point', [ 74.0059, 40.7127 ])
.exec()
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Query("object", "movie")
.geoIntersects('Point', [ 74.0059, 40.7127 ])
.exec(function(err,res) {
// response
})
Find and return records that intersect on the specified coordinates.
The $geoIntersects
MongoDB operator accepts a GeoJSON object.
The geoIntersects
SDK method accepts a GeoJSON object.
For more information about finding records within a geometric boundray, see the MongoDB documention for $geoIntersects.
Within Proximity To A Point
curl -X "GET" 'https://stamplaykb.stamplayapp.com/api/cobject/v1/question?where=\{"_geolocation":\{"$near":\{"$geometry":\{"type":"Point","coordinates":\[74.0059,40.7127\]\}\}\}\}'
Stamplay.Query("object", "dinners")
.near('Point', [ 74.0059, 40.7127 ], 500 )
.exec()
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Query("object", "dinners")
.near('Point', [ 81.0039, 70.4127 ], 500, 100 )
.exec(function(err,res) {
// response
})
Find records within proximity to a geographic point.
The $near
MongoDB operator accepts a GeoJSON Point.
The near
SDK method accepts a GeoJSON Point.
More details about $near on MongoDB docs.
Within Proximity To A Point (Near Sphere)
curl -X "GET" 'https://stamplaykb.stamplayapp.com/api/cobject/v1/question?where=\{"_geolocation":\{"$near":\{"$geometry":\{"type":"Point","coordinates":\[74.0059,40.7127\]\}\}\}\}'
Stamplay.Query("object", "dinners")
.nearSphere('Point', [ 74.0059, 40.7127 ], 1000 )
.exec()
.then(function(res) {
// success
}, function(err) {
// error
})
Stamplay.Query("object", "dinners")
.nearSphere('Point', [ 74.0059, 40.7127 ], 500 )
.exec(function(err,res) {
// response
})
Find records within proximity to a geographic point, calculating distances using spherical geometry.
The $nearSphere
MongoDB operator accepts a GeoJSON Point.
The nearSphere
SDK method accepts a GeoJSON Point.
More details about $nearSphere on MongoDB docs.
Code Blocks
When it comes to handle complex logic application, Flows may not be enough, and the need for a bit of custom logic becomes greater.
Code Blocks make this possible. With Code Blocks, you can add custom NodeJS server side logic when necessary, and let us do the heavily lifting when it's not.
Setup
To create a Code Block:
- Open the Code Blocks section and click on +Add;
- Insert a name for your code and press Enter.
Stamplay generates a RESTful endpoint, whenever you create a Code Block.
Programming Models
There are three ways of writing custom server side code based on your needs:
-
Simple : when you do not need any external parameters, or the use of the incoming request body.
-
Contextual: when you need to access request body, query parameters and/or secrets.
-
Full Control: when you need access to the raw request and response.
Simple Model
module.exports = function(cb) {
return cb(null, { i_am: 'done'});
}
Within the Simple programming model, you must provide JavaScript code that returns a function which accepts a single argument: a callback.
To indicate completion, the function must call the callback with two arguments: an error, and the result.
The result, or the second argument in the callback, will be the response to the originating request, or the destination (i.e. Execution of a Task after a Code Block executes.) request body.
When the callback is invoked, the result value or an error will be serialized as JSON and sent back to the caller as application/json
Content-type.
Contextual Model
module.exports = function(context, cb) {
return cb(null, { hello: context.data.name });
}
A more advanced version of the programming model allows you to return a function that accepts two arguments: a context
and a callback
.
The context
parameter is a JavaScript object with query
, body
and secrets
properties:
- the
query
property will contain the query parameters - the
body
property will let you access the request body when the Code Block is invoked using an HTTP verb that supports a payload and request has aContent-Type
header of eitherapplication/x-www-form-urlencoded
orapplication/json
- the
secrets
property will allow access to the secrets saved within the Code Block
Full Control Model
module.exports = function(context, req, res) {
res.writeHead(200, { 'Content-Type': 'application/json'});
var result = { "hello" : "world" };
return res.end(JSON.stringify(result));
};
The most flexible programming model allows you to take full control over the HTTP request
and response
.
The context
argument won't contain the body
property, you will have to parse it on your own by either using a Node.js library or listening by the data
and end
events on the req
object.
Note that this programming model does not have a concept of a callback. Ending the HTTP response indicates completion.
Express application
const express = require('express');
const Webtask = require('webtask-tools');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.get('/', function (req, res) {
console.log(req.webtaskContext.secrets);
return res.sendStatus(200);
});
module.exports = Webtask.fromExpress(app);
You can write an Express application in a Code Block by mimicking this code.
You can access secrets from the req.webtaskContext.secrets
parameter.
Executing Code Blocks
Code Blocks can be used to implement custom logic and have it available as an API endpoint, for this reason they support any HTTP method. In a nutshell you can execute custom Node.js code with a HTTP call.
To execute a Code Block all you need to do is to send a HTTP request to the Code Block API endpoint that you can see in the Snippets.
Depending from the HTTP method, you can pass data to the Code Block within the body of the request or via query parameters (see below).
curl -X "POST" "https://APPID.stamplayapp.com/api/codeblock/v1/run/{codeblock_name}?name=Stamplay&bar=foo" \
-H "Content-Type: application/json" \
-d "{\"message\":\"Hello\"}"
var data = { message : "Hello"}
var params = { name : "Stamplay", bar : "foo"}
//Stamplay.Codeblock("codeblock_name").run() sends a POST request by default
Stamplay.Codeblock("codeblock_name").run(data, params)
.then(function(err) {
// success
}, function(err) {
// error
})
var data = { message : "Hello"}
var params = { name : "Stamplay"}
//Stamplay.Codeblock("codeblock_name").run() sends a POST request by default
Stamplay.Codeblock("codeblock_name").run(data, params, function(err, res) {
// manage the response and the error
})
Query parameters
You can pass parameters to the Code Block using URL query string of the Code Block request. All URL query parameters except the reserved ones (e.g. user
) will be propagated to the code when it runs. To take advantage of this feature, define your JavaScript function such that it accepts two arguments instead of one: the context
and the callback cb
.
All allowed URL query parameters of the Code Block request will be provided to the Code Block code in the form of context.query
JavaScript object.
Switch to Javascript or NodeJS view to see the Code Block sample
module.exports = function(context, cb) {
return cb(null, "Hello, " + context.query.name);
}
module.exports = function(context, cb) {
return cb(null, "Hello, " + context.query.name);
}
Try it out
You can try it out with curl
or with our SDKs. Usually query parameters are passed when using GET
requests so the examples show how to execute a Code Block with a GET request:
curl -X "GET" "https://APPID.stamplayapp.com/api/codeblock/v1/run/{codeblock_name}?name=Stamplay" \
-H "Content-Type: application/json" \
var params = { name : "Stamplay"}
//GET
Stamplay.Codeblock("codeblock_name").get(params, function(err, res) {
// manage the response and the error
})
//GET
var params = { name : "Stamplay"}
Stamplay.Codeblock("codeblock_name").get(params, function(err, res) {
// manage the response and the error
})
Body parameters
Parameters can be passed the Code Block also using body
parameters of a POST
, PATCH
or PUT
request. All the requestbody
except the reserved ones (e.g. user
) will be propagated to the code when it runs. To take advantage of this feature, define your JavaScript function such that it accepts two arguments instead of one: the context
and the callback cb
.
All allowed URL query parameters of the Code Block request will be provided to the Code Block code in the form of context.body
JavaScript object.
Switch to Javascript or NodeJS view to see the Code Block sample
module.exports = function(context, cb) {
cb(null, "Just received this, " + context.data.bodyparam);
}
module.exports = function(context, cb) {
cb(null, "Just received this, " + context.data.bodyparam);
}
Try it out
You can try it out with curl
or with our SDKs. Usually query parameters are passed when using GET
requests so the examples show how to execute a Code Block with a POST
, PATCH
or PUT
request:
curl -X "POST" "https://APPID.stamplayapp.com/api/codeblock/v1/run/{codeblock_name}" \
-H "Content-Type: application/json" \
-d "{\"bodyparam\":\"Stamplay\"}"
curl -X "PATCH" "https://APPID.stamplayapp.com/api/codeblock/v1/run/{codeblock_name}" \
-H "Content-Type: application/json" \
-d "{\"bodyparam\":\"Stamplay\"}"
curl -X "PUT" "https://APPID.stamplayapp.com/api/codeblock/v1/run/{codeblock_name}" \
-H "Content-Type: application/json" \
-d "{\"bodyparam\":\"Stamplay\"}"
//POST
var data = { bodyparam : "Stamplay"}
Stamplay.Codeblock("codeblock_name").post(data)
.then(function(err) {
// success
}, function(err) {
// error
})
//PUT
Stamplay.Codeblock("codeblock_name").put(data)
.then(function(err) {
// success
}, function(err) {
// error
})
//PATCH
Stamplay.Codeblock("codeblock_name").patch(data)
.then(function(err) {
// success
}, function(err) {
// error
})
var data = { bodyparam : "Stamplay"}
//POST
Stamplay.Codeblock("codeblock_name").post(data, null, function(err, res) {
// manage the response and the error
})
//PUT
Stamplay.Codeblock("codeblock_name").put(data, null, function(err, res) {
// manage the response and the error
})
//PATCH
Stamplay.Codeblock("codeblock_name").patch(data, null, function(err, res) {
// manage the response and the error
})
User context data
When executing a Code Block, you are able to pass in data, which is set to the context.body
property. If an active user session is in place from the originating request, the user of the current session will be placed inside context
on context.body.user
.
module.exports = function(context, cb) {
//context.data contain the request body parameters
var greet = "Hello, ";
//Show data about logged user
console.log("User with Id" + context.data.user._id + " is logged");
//Return a JSON response that includes logged User attribute
return cb(null, { message : greet + " " + context.data.user.displayName + "!" });
};
// switch to javascript or nodejs to read Code Block sample
module.exports = function(context, cb) {
//context.data contain the request body parameters
var greet = "Hello, ";
//Show data about logged user
console.log("User with Id" + context.data.user._id + " is logged");
//Return a JSON response that includes logged User attribute
cb(null, { message : greet + " " + context.data.user.displayName + "!" });
};
Storage
Sometimes your code needs just a little bit of persistent storage, and using a full database feels like too much. Code Blocks code can durably store a single JSON document up to 500KB in size using built-in storage. With simple get/set APIs and basic conflict detection, this is frequently all you need.
Reading data
module.exports = function(context, cb) {
context.storage.get(function (error, data) {
if (error) return cb(error);
// ...
});
}
Use the context.storage.get
API to retrieve a previously stored document.
In the absence of error, the data will contain your previously stored document, or null if no document was stored.
Writing data
module.exports = function(context, cb) {
context.storage.get(function (error, data) {
if (error) return cb(error);
data = data || { counter: 1 };
context.storage.set(data, function (error) {
if (error) return cb(error);
// ...
});
});
}
Use the context.storage.set
API to save a document.
In the absence of error, the data has been successfuly persisted.
Resolving conflicts
module.exports = function(context, cb) {
context.storage.get(function (error, data) {
if (error) return cb(error);
data = data || { counter: 1 };
var attempts = 3;
context.storage.set(data, function set_cb(error) {
if (error) {
if (error.code === 409 && attempts--) {
// resolve conflict and re-attempt set
data.counter = Math.max(data.counter, error.conflict.counter) + 1;
return context.storage.set(data, set_cb);
}
return cb(error);
}
// ...
});
});
}
When many instances of your Code Block attempt to persist the document simultaneously, conflicts may arise. A conflict occurs when the code calls the set
operation, and the value of the document in the database is different from the value that was read last by that instance of a webtask. Code Block runtime automatically detects conflicts and allows you to resolve them using an application-specific logic before re-attempting the set
call.
The absence of error in the callback of set
indicates there were no conflicts and the operation persisted the data successfully.
Forcefully writing data
module.exports = function(context, cb) {
context.storage.set({ counter: 1 }, { force: 1 }, function (error) {
if (error) return cb(error);
//...
});
}
Sometimes you want to disregard the possibility of a conflict and forcefully override whatever data may already be persisted. This can be done with the force
option.
Secret Parameters
You can create a Code Block that includes public or secret parameters. These parameters are made available to the Code Block code when it runs. This mechanism provides a convenient way to equip your Code Block with secret credentials necessary to communicate with external systems while preventing disclosure of these credentials to third parties.
For example, you could write a Code Block that sends an HTTP request to your private API and you need to use a secret token to authorize this request. The secret token to call your API can then be stored encrypted in the Code Block as a secret
, only to be decrypted and provided to your Code Block code when it runs.
Code Blocks allow you to securely store these parameters within the Secrets area.
Adding Secrets
Five steps are required in order to save a secret value:
- Navigate to the Secrets area, under the wrench icon.
- Choose Add Secret.
- Click the Add button.
- Type the key in which the secret will be saved and the value that the secret should have
- Click Save button.
Now your secret has been added and is ready for use within the Code Block.
Accessing Secrets
module.exports = function(context, cb) {
return cb(null, { pass_this_secret : context.secrets.name });
}
In order to access secrets you need to use the Contextual or the Full Control programming model.
You'll find your secrets in the context.secrets
property in the key that you've specified from the Stamplay Editor.
Example shown uses the Contextual programming model.
NPM Modules
const Stamplay = require('stamplay@1.0.6');
const _ = require('lodash@4.8.2');
module.exports = function (context, cb) {
const stamplay = new Stamplay('appId', context.secrets.apiKey);
const body = context.body;
stamplay.Object('movie').save(body, (err, res) => {
return cb(null, JSON.parse(res).data);
});
};
When using Code Blocks you can rely on all the public Node.js modules available on NPM.
In order to correctly import the required node modules inside the Code Block, you need to declare them in the NPM Modules settings available under the wrench icon.
Common Errors
These are some of the most common errors that you may encounter when writing Code Blocks:
Async code not handled properly.
If you're writing code in Node.js, async code is the way to go. If you're having problems syncronizing your code please consider the use of libraries such as q or async which are available in our modules.
I’ve configured a Flow that says “On Code Block run then …” but it’s not working.
There are several reason why the Flow may not be triggered:
Flows work only if the output has as Content-Type application/json
: if you’re using the Simple or Context way to write a Code Block you can just pass null as the first argument (which is the error) and an object to the final callback, and the Flow will be triggered in the right way.
If you’re using the Full Control programming model, make sure to return application/json
as Content-Type.
A flow is triggered only if the Code Block returns a status code between 200 and 299.
A Code Block can currently be executed using POST
, GET
, PUT
, PATCH
or DELETE
method, please ensure that you're using the right HTTP verb.
Logs
If you need to debug your Code Block to see how it behaves, check the Logs tab and you'll be able to see the request and response body of each execution.
Moreover you can check out the console.log
output from the real time console that's available just below your source code.
Retention
Logs are automatically deleted after two weeks.
If you have different needs, please let us know.
Webhooks
Webhooks are "user defined HTTP callbacks".
With Stamplay, Webhooks can be used as custom event triggers for 3rd-Party Integrations, Code Blocks, or Core Services.
Creating Webhooks
To create a webhook, visit the Stamplay Editor for the application you would like to add a webhook for.
Navigate to the Webhooks section, enter a name for your Webhook and Create.
!(Web Hook Create)[images/webhook.create.png]
Any Webhook created is is available at:
Using Webhooks
Webhooks can be used to capture events and used to pass data along to that event.
To post data to a Webhook, make a POST
request to a webhook url you have made in the Stamplay editor, including any data to pass into the Webhook as the request body.
To post data to a Webhook, use the post
method on Stamplay.Webhook("webhook_id")
, include any data to pass into the Webhook as the first method argument.
curl -X "POST" "https://APP-ID.stamplayapp.com/api/webhook/v1/:webhook_id/catch" \
-H "Content-Type: application/json" \
-d "{\"name\":\"John\"}"
Stamplay.Webhook("webhook_id")
.post({ name : "Johne" })
.then(function(res) {
// success
}, function(err) {
// error
})
// no method
Stripe
A first class API layer for integrating Stripe into a Stamplay application.
Customers
Stripe customers allow you to perform recurring charges and track multiple charges that are associated with the same customer.
Add Customer
curl -X "POST" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers" \
-H "Content-Type: application/json" \
-d "{\"userId\":\"546dc9f188104fee05000006\"}"
Stamplay.Stripe.createCustomer("userId")
.then(function(res) {
// success
},
function(err) {
// error
})
// no method
The JSON response looks like this.
{
"__v":0,
"livemode" : false,
"customer_id" : "cus_8GrAxVnGSGHKxv",
"userId" : "571021095743954537b8c0cd",
"appId" : "APP-ID",
"_id" : "57102131da5d4db251c71c76",
"dt_create" : "2016-04-14T23:01:05.995Z",
"subscriptions" : [],
"billingHistory" : [],
"id" : "57102131da5d4db251c71c76"
}
Add a new customer on Stripe.
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to add as a Stripe Customer |
Delete Customer
curl -X "DELETE" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/546dc9f188104fee05000006"
// no method
var userId = '546dc9f188104fee05000006';
Stamplay.Stripe.deleteCustomer(userId, function(err, res) {
// response
})
The JSON response looks like this.
{
"deleted": true,
"id": "cus_9HuvMRmZlnuYg9"
}
Deletes a customer from Stripe.
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to delete from Stripe |
Subscriptions
Subscriptions allow you to charge a customer's card on a recurring basis. A subscription ties a customer to a particular plan you've created.
Fetch User Subscription
curl -X "GET" "https://stripe-docs.stamplayapp.com/api/stripe/v1/customers/:userId/subscriptions/:subscriptionId"
Stamplay.Stripe.getSubscription("userId",
"subscriptionId")
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"id":"sub_8GrYtVQuzArBMy",
"object":"subscription",
"application_fee_percent":null,
"cancel_at_period_end":false,
"canceled_at":null,
"current_period_end":1463268296,
"current_period_start":1460676296,
"customer":"cus_8GrAxVnGSGHKxv",
"discount":null,
"ended_at":null,
"metadata":{},
"plan":{
"id":"subscription_one",
"object":"plan",
"amount":999,
"created":1460675091,
"currency":"usd",
"interval":"month",
"interval_count":1,
"livemode":false,
"metadata":{},
"name":"Subscription One",
"statement_descriptor":"Sub One",
"trial_period_days":null,
"statement_description":"Sub One"
},
"quantity":1,
"start":1460676296,
"status":"active",
"tax_percent":null,
"trial_end":null,
"trial_start":null
}
Retrieve a user subscription by a subscription ID.
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of a user with a subscription |
|
subscriptionId |
the Stripe identifier of the subscription to fetch |
Fetch User's Subscriptions
curl -X "GET" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/:userId/subscriptions"
Stamplay.Stripe.getSubscriptions("userId",
options)
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"object":"list",
"data":[
{
"id":"sub_8GrYtVQuzArBMy",
"object":"subscription",
"application_fee_percent":null,
"cancel_at_period_end":false,
"canceled_at":null,
"current_period_end":1463268296,
"current_period_start":1460676296,
"customer":"cus_8GrAxVnGSGHKxv",
"discount":null,
"ended_at":null,
"metadata":{},
"plan":{
"id":"subscription_one",
"object":"plan",
"amount":999,
"created":1460675091,
"currency":"usd",
"interval":"month",
"interval_count":1,
"livemode":false,
"metadata":{},
"name":"Subscription One",
"statement_descriptor":"Sub One",
"trial_period_days":null,
"statement_description":"Sub One"
},
"quantity":1,
"start":1460676296,
"status":"active",
"tax_percent":null,
"trial_end":null,
"trial_start":null
}
],
"has_more":false,
"url":"/v1/customers/cus_8GrAxVnGSGHKxv/subscriptions"
}
Retrieve a user's subscriptions.
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to fetch subscriptions for |
Add A Subscription
Add a new subscription to a Stripe customer.
curl -X "POST" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/:userId/subscriptions" \
-H "Content-Type: application/json" \
-d "{\"planId\":\"stripePlanId\"}"
Stamplay.Stripe.createSubscription("userId",
"planId")
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"id":"sub_8GrYtVQuzArBMy",
"object":"subscription",
"application_fee_percent":null,
"cancel_at_period_end":false,
"canceled_at":null,
"current_period_end":1463268296,
"current_period_start":1460676296,
"customer":"cus_8GrAxVnGSGHKxv",
"discount":null,
"ended_at":null,
"metadata":{},
"plan":{
"id":"subscription_one",
"object":"plan",
"amount":999,
"created":1460675091,
"currency":"usd",
"interval":"month",
"interval_count":1,
"livemode":false,
"metadata":{},
"name":"Subscription One",
"statement_descriptor":"Sub One",
"trial_period_days":null,
"statement_description":"Sub One"
},
"quantity":1,
"start":1460676296,
"status":"active",
"tax_percent":null,
"trial_end":null,
"trial_start":null
}
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to add a subscriptions for |
|
planId |
the Stripe identifier of the subscription to add |
Update Subscription
Update a subscription for a Stripe customer.
curl -X "PUT" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/:userId/subscriptions/:subscriptionId" \
-H "Content-Type: application/json" \
-d "{\"options\":\"{ \"plan\" : \"subscription_one\"}\"}"
Stamplay.Stripe.updateSubscription("userId", "planId",
{ "plan : subscription_one" })
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"id":"sub_8GrYtVQuzArBMy",
"object":"subscription",
"application_fee_percent":null,
"cancel_at_period_end":false,
"canceled_at":null,
"current_period_end":1463268296,
"current_period_start":1460676296,
"customer":"cus_8GrAxVnGSGHKxv",
"discount":null,
"ended_at":null,
"metadata":{},
"plan":{
"id":"subscription_two",
"object":"plan",
"amount":1999,
"created":1460676804,
"currency":"usd",
"interval":"month",
"interval_count":1,
"livemode":false,
"metadata":{},
"name":"Subscription Two",
"statement_descriptor":"Sub Two",
"trial_period_days":null,
"statement_description":"Sub Two"
},
"quantity":1,
"start":1460695662,
"status":"active",
"tax_percent":null,
"trial_end":null,
"trial_start":null
}
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to update a subscriptions for |
|
subscriptionId |
the Stripe _id of the subscription to update |
|
options |
a set of options for updating a subscription, see Stripe Documentation for details |
Remove Subscription
Remove a subscription from a Stripe customer.
curl -X "DELETE" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/:userId/subscriptions/:subscriptionId" \
-H "Content-Type: application/json" \
-d "{\"options\":\"{}\"}"
Stamplay.Stripe.deleteSubscription("userId", "subscriptionId", options)
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"id":"sub_8GrYtVQuzArBMy",
"object":"subscription",
"application_fee_percent":null,
"cancel_at_period_end":false,
"canceled_at":1460695945,
"current_period_end":1463268296,
"current_period_start":1460676296,
"customer":"cus_8GrAxVnGSGHKxv",
"discount":null,
"ended_at":1460695945,
"metadata":{},
"plan":{
"id":"subscription_two",
"object":"plan",
"amount":1999,
"created":1460676804,
"currency":"usd",
"interval":"month",
"interval_count":1,
"livemode":false,
"metadata":{},
"name":"Subscription Two",
"statement_descriptor":"Sub Two",
"trial_period_days":null,
"statement_description":"Sub Two"
},
"quantity":1,
"start":1460695662,
"status":"canceled",
"tax_percent":null,
"trial_end":null,
"trial_start":null
}
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to remove a subscriptions for |
|
subscriptionId |
the Stripe _id of the subscription to update |
Cards
You can store multiple cards on a customer in order to charge the customer later.
Fetch A User's Card
Retrieve a Stripe customer's card.
curl -X "GET" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/:userId/cards"
Stamplay.Stripe.getCreditCard("userId")
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"last4":"4242",
"fingerprint":"0YBm29b7kpk2tbQe",
"exp_year":"2017",
"exp_month":"12",
"cvc_check":"pass",
"country":"US",
"card_id":"card_180Jb6JGp443qx8tOrIZ89PM",
"brand":"Visa"
}
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to fetch cards for |
Add A Card
Add a new card to a Stripe customer.
Obtain a token using Stripe.js.
curl -X "POST" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/:userId/cards" \
-H "Content-Type: application/json" \
-d "{\"token\":\"card_token\"}"
Stamplay.Stripe.createCreditCard("userId",
"token")
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"card_id":"card_180Jb6JGp443qx8tOrIZ89PM",
"last4":"4242",
"brand":"Visa",
"exp_month":"12",
"exp_year":"2017",
"fingerprint":"0YBm29b7kpk2tbQe",
"country":"US",
"cvc_check":"pass"
}
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to add a new card for |
|
token |
a token obtained from Stripe.js |
Update A Card
Update a card for a Stripe customer.
Obtain a token using Stripe.js.
curl -X "PUT" "https://APP-ID.stamplayapp.com/api/stripe/v1/customers/:userId/cards" \
-H "Content-Type: application/json" \
-d "{\"token\":\"card_token\"}"
Stamplay.Stripe.updateCreditCard("userId",
"token")
.then(function(res) {
// success
},
function(err){
// error
})
// no method
The JSON response looks like this.
{
"last4":"4242",
"fingerprint":"0YBm29b7kpk2tbQe",
"exp_year":"2017",
"exp_month":"12",
"cvc_check":"pass",
"country":"US",
"card_id":"card_180Jb6JGp443qx8tOrIZ89PM",
"brand":"Visa"
}
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to update a card for |
|
token |
a token obtained from Stripe.js |
Charges
Create Charge
Charge a Stripe customer's card.
curl -X "POST" "https://APP-ID.stamplayapp.com/api/stripe/v1/charges" \
-H "Content-Type: application/json" \
-d "{\"userId\":\"51e554184d88a4452c002233\",
\"token\":\"card_id\",
\"amount\":500,
\"currency\":\"USD\"}"
Stamplay.Stripe.charge("userId",
"token",
"amount",
"currency")
.then(function(res) {
// Success
},
function(err){
// Handle Error
});
// no method
The JSON response looks like this.
{
"id":"ch_180P6uJGp443qx8tho9DlZ5c",
"object":"charge",
"amount":1699,
"amount_refunded":0,
"application_fee":null,
"balance_transaction":"txn_180P6vJGp443qx8twAGVDTIl",
"captured":true,
"card":{
"id":"card_180Jb6JGp443qx8tOrIZ89PM",
"object":"card",
"address_city":null,
"address_country":null,
"address_line1":null,
"address_line1_check":null,
"address_line2":null,
"address_state":null,
"address_zip":null,
"address_zip_check":null,
"brand":"Visa",
"country":"US",
"customer":"cus_8GrAxVnGSGHKxv",
"cvc_check":null,
"dynamic_last4":null,
"exp_month":12,
"exp_year":2017,
"fingerprint":"0YBm29b7kpk2tbQe",
"funding":"credit",
"last4":"4242",
"metadata":{},
"name":null,
"tokenization_method":null
},
"created":1460696596,
"currency":"usd",
"customer":"cus_8GrAxVnGSGHKxv",
"description":null,
"destination":null,
"dispute":null,
"failure_code":null,
"failure_message":null,
"fraud_details":{},
"invoice":null,
"livemode":false,
"metadata":{},
"order":null,
"paid":true,
"receipt_email":"isaiahgrey@gmail.com",
"receipt_number":null,
"refunded":false,
"refunds":{
"object":"list",
"data":[],
"has_more":false,
"total_count":0,
"url":"/v1/charges/ch_180P6uJGp443qx8tho9DlZ5c/refunds"
},
"shipping":null,
"source":{
"id":"card_180Jb6JGp443qx8tOrIZ89PM",
"object":"card",
"address_city":null,
"address_country":null,
"address_line1":null,
"address_line1_check":null,
"address_line2":null,
"address_state":null,
"address_zip":null,
"address_zip_check":null,
"brand":"Visa",
"country":"US",
"customer":"cus_8GrAxVnGSGHKxv",
"cvc_check":null,
"dynamic_last4":null,
"exp_month":12,
"exp_year":2017,
"fingerprint":"0YBm29b7kpk2tbQe",
"funding":"credit",
"last4":"4242",
"metadata":{},
"name":null,
"tokenization_method":null
},
"source_transfer":null,
"statement_descriptor":null,
"status":"paid",
"statement_description":null
}
Attribute | Optional | |
---|---|---|
userId |
the Stamplay _id of the user to charge |
|
token |
the Stripe identifier for the customer card to charge | |
amount |
the amount in cents to charge | |
currency |
a 3-letter ISO code for currency, default USD |
Web Hosting
Stamplay Hosting provides you with the tools to host static or dynamic websites that are hooked up to our backend.
You can upload arbitrary static web content or create dynamic web apps, using the JavaScript SDK on the client side.
This guide shows you how to easily deploy and host your app’s static assets (HTML, CSS, JavaScript, etc.) with our production-grade hosting service.
Stamplay Command Line Tool
The Stamplay Command Line (CLI) Tool can be used to:
-
- Administer your Stamplay account
-
- Interact with Stamplay Platform, our product to host your static HTML, JS, CSS, images, etc.
-
- Test you application locally.
The Stamplay CLI requires Node.js and NPM, which can both be installed by following the instructions at https://nodejs.org/. Installing Node.js also installs NPM by default.
Once you have Node.js and NPM installed, you can install the Stamplay command line tools via NPM.
npm install -g stamplay-cli
// sudo may be required depending on your system permissions
// sudo npm install -g stamplay-cli
This installs stamplay
as a globally available command interface.
stamplay.json
stamplay init
The stamplay.json
file, when create is typically in the root of your project's directory.
{
"appId": "yourAppId",
"apiKey": "yourAppApiKey",
"public": "./",
"ignore": [
"stamplay.json",
"**/.*",
"**/node_modules/**"
]
}
This required file is used to configure which files are published upon deployment, set customer headers, etc.
To generate a stamplay.json
file, run the init
CLI command.
After running the command, you will be prompted to enter the APP ID
and API Key
of the application.
The default stamplay.json
file will look like the example:
An optional headers
property is available to define browser side caching of static resources such as libraries or images.
Caching removes the need to load static libraries every time. This is helpful in a production enviornment to help speed up load times, and even reduce server load. See below for more details.
appId and apiKey
"appId": "yourAppId",
"apiKey": "yourAppApiKey"
The appId
and apiKey
are used by the command line tool as authentication parameters.
public
"public" : "./"
The public
property tells the command line which directory to upload to Stamplay. This directory must be inside the project directory and must exist.
The default value is the root directory or your project. This directory is also the one used by the command line tool when running the local server.
ignore
"ignore" : [
"stamplay.json",
"**/.*",
"**/node_modules/**"
]
The ignore
specifies which files to ignore on deploy. It can take glob definitions in the same way git handles .gitignore
.
headers
"headers": [
{
"source" : "**/*.@(jpg|jpeg|gif|png)",
"headers" : [
{
"key" : "Cache-Control",
"value" : "max-age=7200"
}
]
},
{
"source" : "404.html",
"headers" : [
{
"key" : "Expires",
"value" : "1y"
}
]
}
]
The headers
is an optional parameter in the stamplay.json
file.
It is only available to be used only if your stamplay-cli
version is 1.3.9
or greater.
This property is an array of header objects. Each object specifies:
source
A file glob pattern to be matched.
headers
A headers property of its own, as an array of header objects for the glob pattern source.
Each specifies a key and value property.
The key designates the header type, and value is the value of the header type itself.
Each definition must have a source
key that is matched against the original request path using glob notation; and must also have the array of headers applied, each with a valid key and a value.
The following header types are supported:
Expires
The time in the Expires
header is computed as a sum of the current time and time specified in the directive.
Allowed values for the Expires
header are minutes : m
, hours : h
, days : d
, weeks : w
, years : y
.
For example, 5d
is 5 days, or 120m
is 120 minutes.
Cache-Control
The time in the Cache-Control
header is represented in seconds.
For example, 3600
is 3600 seconds.
App Deploy
stamplay deploy
To deploy a new release, run the deploy
with the CLI.
This pushes the public
directory as defined with the stamplay.json
to Stamplay, which the deploys your static app to your stamplayapp.com domain.
Rollback
To rollback to a previous deploy, run the rollback
CLI command.
stamplay rollback
You'll be prompted to pick one of your previous deploys from a list and your app will be restored.
App Development
stamplay start
You can run the Stamplay command line tool to build your app in development mode on your local environment. This will make the tool initialize a local server that will serve your app on http://localhost:8080.
To run your application locally, run the start
CLI command.
Applications built with Stamplay must have an index.html
file at root level of the public
property defined in the stamplay.json
.
By default the root level defined in stamplay.json
public setting is "./"
.
The index.html
will be served when serving the application locally on localhost, or at https://APPID.stamplayapp.com after deployment.
Open In Browser
To launch the live version of your application, run the open
CLI command.
stamplay open
CLI Updates
You can update the Stamplay CLI by running npm install
for the stamplay-cli
npm package with the -g
global option.
npm install -g stamplay-cli
Thi will update your Stamplay command line tool to the latest version.
Custom Domains and SSL
Users on a paid plan can also host content at a custom domain name.
Setup
To setup a custom domain, open the Stamplay Editor.
In the Stamplay Editor, in the Dashboard section. Select Hosting section, then Use A Custom Domain and add the value www.mybeautifulwebsite.com to the App Domain field.
On your DNS provider, add a CNAME record from www.mybeautifulwebsite.com to mydemoapp.stamplayapp.com to begin sending traffic to your hosted app.
After completing these steps, www.mybeautifulwebsite.com will serve the same content as mydemoapp.stamplayapp.com.
If you want to serve content at an apex domain such as example.com, you might have trouble with the steps above because root domains generally don't support CNAME records. To support this situation, you must configure ALIAS, ANAME or A records with your DNS provider.
If your DNS provider supports ALIAS records (such as with DNSimple) or ANAME records (such as with DNS Made Easy), you may choose to create an ALIAS or ANAME record to mydemoapp.stamplayapp.com instead (Note: some DNS providers allow an apex domain configured with an ALIAS record to point to some other domain name).
Subdomains of up to one level of depth are supported.
Deeper subdomains, such as my.beautiful.website.com, are not allowed.
Pretty URLs
To enable the url rewrite on the server side for single page applications, all you need to do is navigate to the Dashboard section then to Hosting section inside the Stamplay Editor, and check the box in the middle of the configuration under the URL Rewriting heading to enable all entry points to your domain, to point to the index.html
page.
Other steps still need to be taken to setup Pretty Urls, and differ among frameworks and libraries.
For the best support on this issue, search for solution specific to the framework or library you are using for routing.
CORS Enabled Domains
To enabled a domain for Cross Origin Requests, add the domain to the list inside the Dashboard section of the Stamplay Editor.
The field is under the CORS enabled domains heading. You can add the wildcard *
to allow all origins. This is however not recommended.
Domain Ownership & SSL
Stamplay will handle provisioning an SSL certificate for your domain and serving your content over a CDN. However, before setting up your SSL certificate, you will need to update the DNS entries for your domain by a CNAME entry.
The entries will be available via email once you begin the process of adding a custom domain. Depending on your domain name server host, this verification step may be instant or it may take an hour or more.
Once domain ownership is verified, we will provision an SSL certficate for your domain and deploy it across our global CDN. This process can take up to 48 hours, and you will receive an email when it is complete.