Introduction
BaasBox is a complete solution to implement the back end of your applications.
It is available as a product released under the Apache 2 license
The latest version is 0.9.4
You can access all sections using the sidebar on the left. The documentation explains:
the BaasBox features (server side)
the SDK features
For a complete list of changes and new features, see the changelog
The Android SDK JavaDoc is here
Our tutorials will allow you to rapidly have a first result of what BaasBox can give you. Enjoy!
1 2 | In this section you can find code examples for every platform we address.
Click on any tab above to choose the platform of your interest.
|
1 2 3 4 5 6 7 8 9 | You have two ways to install the iOS SDK. We suggest cocoapods: just add "pod 'BaasBoxSDK', '~> 0.9.0'" to your pod file. As an alternative you can download this repo (https://github.com/baasbox/iOS-SDK) and drag and drop the BaasBox-iOS-SDK folder on Xcode. Finally insert the following statement wherever you need BaasBox functionalities #import "BAAClient.h" and you are good to go. Note for Swift projects. As of Xcode 6.1 you need to drag .h and .m files (and not the enclosing folder), otherwise you are not asked to create a bridging header. Once you have created one, add the following statement and you are good to go: #import "BAAClient.h" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /* The Android SDK is distributed as a jar. To get started download it from the download section of the website (https://opensource.bassbox.com/), and put it in your libs folder. To initialize the client, add the following code to your application class. */ public class MyApp extends Application{ private BaasBox client; @Override public void onCreate() { BaasBox.Builder builder = new BaasBox.Builder(this); client =builder.setApiDomain("127.0.0.1") .setAppCode("YOUR-APP-CODE") .init(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 | /* You can download the SDK from the [download page](https://opensource.baasbox.com). To use the SDK just import jQuery and the `baasbox.js` in the head section of your page like this. */ <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="../baasbox.js"></script> /* The jQuery cookie plugin, needed to save authentication tokens, is already included at the top of the `baasbox.js` file. The SDK also supports [Zepto](http://zeptojs.com/). */ |
Installation
System Requirements Java VM 8 or later. BaasBox is compiled with Java 1.8.
- Download the latest version here.
- Unzip the
baasbox-x.x.zip
file wherever you want. - Type:
- run
start.bat
(on Windows) ./start
(on *nix) You might need to grant execution permissions viachmod +x ./start
- run
BaasBox will start and it will listen on port 9000. Visit http://localhost:9000/ with your preferred browser. If everything worked fine, the BaasBox logo should appear. Now you can open the administrator console: http://localhost:9000/console For further details about the console, you can read console. That’s all! BaasBox is ready to go and to serve your apps! To stop the server just halt (Ctrl-C) the shell script.
BaasBox is also available as a cloud service already configured and ready to use.
Configuration
BaasBox does not need any configuration to start. However, you can modify many parameters to fit your specific needs. You can act on different setting levels depending on your goal. The setting levels are:
To set an option you have to type it as a start script parameter.
JVM Parameters
1 | ./start -XX:MaxPermSize=64m
|
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
Since BaasBox runs on top of a Java Virtual Machine, you can use any JVM options to perform a fine tuning of your BaasBox. By default no options are used. A complete reference to the JVM parameters can be found here.
These settings cannot be modified at runtime.
Play Framework Settings
1 | ./start -Dhttp.port=80
|
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
BaasBox is based on the Play Framework 2.2.4. This means that it accepts all the options available for any Play application. A complete reference of such options can be found here.
These settings cannot be modified at runtime.
BaasBox Settings
There are some settings relating to a specific instance of the BaasBox server, such as, for example, the AppCode. The AppCode is a special code that must be supplied every time an API call is executed. These settings cannot be modified at runtime.
Here are the BaasBox settings you can set:
Key | Description | Default |
---|---|---|
application.secret | The secret key used to secure cryptographics functions | A very long string |
orient.baasbox.path | The path where BaasBox will store the embedded OrientDB data | db/baasbox |
orient.baasbox.backup.path | The path where BaasBox will store the backups | db/backup |
push.baasbox.certificates.folder | The folder where the iOS push certificate will be stored | certificates |
application.code | The AppCode of the instance | 1234567890 |
query.record_per_page | The number of records returned in case of pagination | 20 |
baasbox.wrapresponse | DEPRECATED: it wraps the responses in a JSON object. The SDKs only support the true value. |
true |
baasbox.statistics.system.memory | Disable this if you don’t want memory information when the /admin/dbStatistics API is called | true |
baasbox.statistics.system.os | Disable this if you don’t want OS information when the /admin/dbStatistics API is called | true |
baasbox.startup.dumpdb | it dumps DB information on startup | false |
baasbox.server.accesslog | Enable/disable the access log | true |
These settings cannot be modified at runtime.
App Settings
These are the settings relating to your App. They are stored into the embedded DB and because of this, once they are set, they are read from the DB and you do not have to specify them every time you start BaasBox. The App Settings can be configured via the Administration Console. The settings are split in five sections:
Application
Password Recovery
Images
Push Notifications
Social Login
These settings can be modified at runtime.
The available options for each section are described below.
Application
General options for the App(lication)
Key | Description | Default |
---|---|---|
application.name | The name of your App | BaasBox |
network.http.port | The TCP port used by the App to contact BaasBox. Please note: when behind a reverse proxy, this could be different from the port used by BaasBox | 9000 |
network.http.ssl | Set to true if the BaasBox server is reached via SSL through a reverse proxy. |
false |
network.http.url | The public URL of the BaasBox server. I.e. the URL used by the App to contact BaasBox, without the protocol prefix (i.e. http://) and PORT | localhost |
session_tokens.timeout | The expiration time of the session tokens (in minutes). WARNING: the admin console refreshes the session token every 5 minutes, if you set a value lower than 5, you may experience disconnection from the console. To disable expiration set it to 0. | 0 |
Password Recovery
Options for the Password Recovery feature
(snippetcode)__ Key |
(snippetcode)__ Description |
(snippetcode)__ Default |
---|---|---|
email.expiration.time | Minutes before the reset code expires | 15 |
email.from | The name and address to be specified in the ‘from’ field of the email to send | info@example.com |
email.subject | The subject of the email to send | BaasBox: reset password |
email.template.html | The template (html format) of the email to send to the user when they request a password reset. Please ensure that you have written the keyword $link$ inside the text. This keyword will be replaced with the link that the user has to click on to start the password recovery process. | The text of the email |
network.smtp.authentication | Set to true if the SMTP server requires authentication |
true |
network.smtp.host | IP address or fully qualified name of the SMTP server | mail.example.com |
network.smtp.password | The password required by the SMTP server if it requires authentication. Used only if network.smtp.authentication is set to `true | password |
network.smtp.port | the TCP port of the SMTP server | 25 |
network.smtp.ssl | Enable or disable the SSL protocol for the SMTP server | false |
Images
Options for the server-side images resizing feature
Key | Description | Default |
---|---|---|
image.allows.automatic.resize | Enable or disable automatic resizing of images | true |
image.allowed.automatic.resize.formats | A space-separated-value list of image size, both in px or in % | 25% 50% 75% <=80px |
Push Notifications
Since version 0.8.4, with BaasBox is possible to manage at most three apps for sending push notifications.
i.e. an administration app and a customer app for a store, or it’s possible to distribute one app for free and one app not for free. In this example the apps share the same backend.
New section on console, Push Settings available directly in leftmenu.
N.B.: Apps must be turned on after being configured
Options for the Push Notifications feature
Key | Description | Default |
---|---|---|
profile1.push.sandbox.enable | The value to verify if BaasBox needs to contact the SANDBOX server or the PRODUCTION server for the first app | true i.e. it is in SANDBOX mode |
profile1.push.apple.timeout | The timeout for push notifications on Apple devices for the first app | 0 - no timeout |
profile1.sandbox.android.api.key | The key to send push notifications to Android devices in SANDBOX mode for the first app | |
profile1.sandbox.ios.certificate | The Apple certificate in SANDBOX mode for the first app | |
profile1.sandbox.ios.certificate.password | The password of the Apple certificate in SANDBOX mode for the first app | |
profile1.production.ios.certificate | The Apple certificate in PRODUCTION mode for the first app | |
profile1.production.ios.certificate.password | The password of the Apple certificate in PRODUCTION mode for the first app | |
profile1.push.profile.enable | Enable this profile | false |
profile2.push.sandbox.enable | The value to verify if BaasBox needs to contact the SANDBOX server or the PRODUCTION server for the second app | true i.e. it is in SANDBOX mode |
profile2.push.apple.timeout | The timeout for push notifications on Apple devices for the second app | 0 - no timeout |
profile2.sandbox.android.api.key | The key to send push notifications to Android devices in SANDBOX mode for the second app | |
profile2.sandbox.ios.certificate | The Apple certificate in SANDBOX mode for the second app | |
profile2.sandbox.ios.certificate.password | The password of the Apple certificate in SANDBOX mode for the second app | |
profile2.production.ios.certificate | The Apple certificate in PRODUCTION mode for the second app | |
profile2.production.ios.certificate.password | The password of the Apple certificate in PRODUCTION mode for the second app | |
profile2.push.profile.enable | Enable this profile | false |
profile3.push.sandbox.enable | The value to verify if BaasBox needs to contact the SANDBOX server or the PRODUCTION server for the third app | true i.e. it is in SANDBOX mode |
profile3.push.apple.timeout | The timeout for push notifications on Apple devices for the third app | 0 - no timeout |
profile3.sandbox.android.api.key | The key to send push notifications to Android devices in SANDBOX mode for the third app | |
profile3.sandbox.ios.certificate | The Apple certificate in SANDBOX mode for the third app | |
profile3.sandbox.ios.certificate.password | The password of the Apple certificate in SANDBOX mode for the third app | |
profile3.production.ios.certificate | The Apple certificate in PRODUCTION mode for the third app | |
profile3.production.ios.certificate.password | The password of the Apple certificate in PRODUCTION mode for the third app | |
profile3.push.profile.enable | Enable this profile | false |
Social Login
Options to use the Social Networks as user authenticators
Key | Description | Default |
---|---|---|
social.facebook.enabled | Activate the Facebook authenticator | false |
social.facebook.token | Application Token for the Facebook app | |
social.facebook.secret | Application secret for the Facebook app | |
social.google.enabled | Activate the Google+ authenticator | false |
social.google.token | Application Token for Google+ | |
social.google.secret | Application secret for Google+ |
Override App Settings
1 | ./start -Dbaasbox.settings.Application.session_tokens.timeout.value=30
|
The options and settings defined into the database can be overridden providing new values through CLI parameters.
The stored values are not modified.
To override a specific setting:
baasbox.settings.<section>.<key>.value=<new value>
Where
section is one of:
- Application
- PasswordRecovery
- Push
- Social
- Images
key is one of the keys listed above
Both sections and key names are case-sensitive.
External Configuration File
Instead of passing every single option as a parameter of the start script, you can put all of them in an external file and simply tell BaasBox where this is located.
To use an external file, you have to use the following options and instructions
(keysnippetcode)_____ Key |
(descriptionsnippetcode)_____ Description |
(examplesnippetcode)_____ Example |
---|---|---|
config.file | An external configuration file. You can put all your parameters in a file. This file MUST include the include classpath(“application.conf”) directive, otherwise BaasBox will not work |
-Dconfig.file=baasbox.config |
Regarding the config.file
key, a possible example of an external configuration file may be:
1 2 3 4 5 | include classpath("application.conf") application.code="1234-56789" orient.baasbox.path=db/baasbox |
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
General Overview
BaasBox is a server that makes available a set of functions for the
backend of mobile applications. All you need is a Java Virtual Machine
1.8 or later. BaasBox already has everything you need
for it to work: an application server and a DB server.
BaasBox was born to be simple to use and manage. To migrate a BaasBox instance from a
server to another, you just have to zip the database folder and copy it
into the server target folder. Moreover, it is ready to use without
changing the configuration parameters. You just have to
launch the command ./start
(or start.bat
on Windows) and BaasBox will
run. Should you need it, you can apply customized configuration parameters. See the configuration section.
Available Functions
Available functions are:
Administration console:
- A convenient web based administration console is provided, through which the administrator can manage several features of BaasBox
Content management:
- Definition of “objects collection (AKA documents)”
- Creation, modification and deletion of objects
- Granting and revoking reading/modification/cancellation authorization on single objects
- Queries that allow specifying selection and ordering criteria
- Management of “special” contents called Assets, which may be files of any kind, to which you can associate arbitrary JSON data
Users management:
- Signup, Login, Logout, profile management (private features, public features and so on), forgotten password recovery, link and log-in through Facebook and Google+
- Role management: administrators, registered users, back-office users, creation of new roles.
File management:
- Create and fetch files
- Content and metadata extraction
- ACL
- Images resize
Push notifications:
- Push notifications for iOS and Android devices
DB management:
- Backup/restore and reset the integrated database
REST API Access management:
- Enable/disable groups of REST endpoints from external access
Applied Technology
BaasBox is written mostly in Java, with some code in Scala. It uses the Play Framework 2.2.4 and it incorporates the core of the OrientDB 1.7.10 database. This will allow BaasBox to natively manage the relations between JSON objects and to link objects and queries without using specific abstractions or having to simulate them on the applicative level. OrientDB was recently surveyed and entered Gartner’s Magic Quadrant.
Console
1 2 3 4 5 6 7 | To run the BaasBox server go into its folder and type ./start on Windows systems type start.bat Once the server is up and running, you can access the console by opening the following link: http://127.0.0.1:9000/console |
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
1 | NOTHING HERE. See the 'Shell' Tab |
BaasBox has a web console that allows to manage its behavior and to perform administrative tasks. The console is a responsive one-page web application that performs REST calls to the BaasBox admin APIs. We suppose that BaasBox is deployed on localhost with its default parameters. If you deployed BaasBox the correct way, you can open your browser and open the welcome screen:
Login screen
When you are in the start view, the administrator console is reachable
at the /console
path.
To login in the administrative area you must supply credentials and Application Code to the administrator. By default these values are:
- Username: admin
- Password: admin
- App Code: 1234567890
You can change the App Code at any time by following the instructions shown in the configuration section. By clicking on the question marks, the fields will be filled with the default values.
Dashboard
Once you have logged in, you will see the main dashboard screen:
The web console is based on the Twitter bootstrap and on the Charisma Template project. The dashboard is split into several sections:
- BaasBox version number
- Quick link to the BaasBox site
- Main menu to access all the main sections of BaasBox
- A trace of where you are located
- Number of users and rapid access to the relative section
- Number of documents (objects) stored in the embedded database and rapid access to the relative section
- Number of files stored and rapid access to the relative section
- Quick link to the download on the BaasBox website where you can find the latest version
- Number of collections, documents and total size in one window.
- Here you can see all the latest news about BaasBox. These are feeds from the BaasBox site |News|
- System window:
- Memory: you can find max allocable memory, current allocated memory and current used memory
- OS: you can find name, version, architecture and processors viewed by your OS
- Java: you can find version, vendor and class version of your JDK
- Database: you can find the version with its path and data size
- Access a dialog window to change the password or to logout
- Change password: Just insert old and new passwords, then confirm the new one
- Logout: just logout from the console. Remember that you can also logout from the left menu.
- DB Management: you can create a backup of your DB and import & export
- Roles: you can view and create roles for users
- Files: here you will find the files you have uploaded and you will be able to manage them and work on them
- REST API Access: The REST API Access section allows you to manage which REST endpoints are accessible to non administrator users
- Push. The section where it is possible to enable/disable apps to send push notifications. You can also test your settings sending test messages to registered users
- Plugin installed. The section where it is possibile to write your own plugins.
- See the BaasBox verbose log. Useful to inspect what happens behind the scene and to report detailed bugs
Console settings
By selecting the Settings option in the left menu you can access the settings section. You can choose settings for applications, password recovery, images and push notifications. Each record has the Edit button that allows you to modify its action. See also Settings.
Image resizing
In the settings you can define an array of possible resizing policies for images.
Examples are:
25%
: scales the image to 25%<=80px
: scales the image so that the smallest dimension is at most 80px.
See Retrieve a file on how to use these values.
REST API Access
The REST API Access section allows you to manage which REST endpoints are accessible to non administrator users. Those are grouped by functionality under a Function group. Each record has a button to switch on and off the endpoints in the named group.
Database Management
The item DB Management allows you to perform some operations on the database.
- Restore a previously created backup file
- Create a new backup
- View the list of generated backups
- Reinitialize the database at its initial state. It deletes all the database content.
To create a new backup, you have to click on the “Create a new backup…” button. This operation is asynchronous. BaasBox will freeze the database and it will stop responding to the clients. When the backup is ready you will find it in the list. From that list you can download it or delete it.
To restore a database you have to download a backup file locally, and then use the restore feature.
Server Log
By clicking on this menu item, a new window (or tab) will be opened in your web browser. In this new window, from now on, you will see the BaasBox verbose log (not available on the BaasBox cloud service). This feature is quite useful to know what happens behind the scene without access to the server to inspect the logs.
Push Settings
The Push Settings section allows you to enable/disable apps for sending push notifications. From BaasBox 0.8.4 it is possible to manage apps for sending push notifications. In particular BaasBox support max three apps. It’s possible to switch app settings by the tab section.
- App #1 (Default) is the section for the first app, which is the default app
- App #2 is the section for the second app
- App #3 is the section for third app
For Android Key (Sandbox/Production), remember to check the availability of Google Cloud Messaging for Android, in Google Play Developer Console. If disabled or if Android Key is wrong it will be returned error and no key are stored.
When the settings is configured, is possible to enabled the specific app.
Notice: Is possible to switch mode, with app enabled, only if the settings for the other mode are configured.
Push Test
From here you can send messages and test the API to send push notifications. By default the Payload is:
1 2 3 4 | { "users": ["user1","user2"], "message": "This is a test message!" } |
Into the Server Response section you can see detailed information on which steps BaasBox performed to elaborate the provided JSON.
Users
By selecting the Users option on the menu you can access the users section.
In this section you have the list of all users. A single user has a name, a role (admin, anonymoususer, backofficeuser, registereduser), a creation date, a status and actions. You also have a search tool. If you want to create a new user, click on the New User button and you will see this window:
Collections
By selecting the Collections option on the menu you can access the collection administration page. Collections are a sort of buckets where you can store objects, also known as “documents”.
In this section you have a list of all your collections and you can quickly find them with the search tool. To create a new collection, click on the New Collection button and insert its name, then save the changes.
Documents
Documents are objects stored in the embedded NoSQL database and grouped in “Collections”.
In this section you have the list of all your documents, but you have to select an existing collection at first. In fact you can see all the documents relating to a specific collection. Of course you also have the search tool.
Each document has a unique ID, generated by the server once it is stored. Data documents are stored and retrieved JSON format.
Documents are accessible only by the user who created them. APIs exist to grant and revoke permissions to the single users or roles. See also Grant/Revoke.
Assets
Assets are special objects. They are public by default, but only administrators can create or delete them. They can store arbitrary data (in JSON format), or entire files. Each Asset can store a file and its associated data. Assets do not have IDs generated by the server, but you can, indeed you MUST, assign a unique name to them. You can subsequently use these names to reference the assets.
In this section you have a detailed list of all your assets with information fields like Icon, Name, Meta, Size, Type, Download and Actions. Of course you also have the search tool. If you want to create a new asset, click on the New Asset button and you will see the following window:
Plugins
Since BaasBox 0.9.0 it is possibile to write your own plugin thanks to the Server Side Code (engine).
The home of the plugins section is the following:
To create a new plugin, click on the “New…” button and choose a plugin name.
The names of the plugins must be in the form namespace.plugin_name, the namespace “baasbox” is reserved.
Now you have created a new plugin, here is a brief explanation of the editor page.
- Create a new plugin
- Delete the plugin
- Refresh the plugin list
- Save the plugin
- Activate/deactivate the plugin
- Show/Hide the plugin local storage
- Edit the plugin (you can enter edit mode just by starting to type)
- Enable/Disable the Plugin Log
For further information please check the wiki
SDK
Native SDKs for iOS, Android and Javascript are available. They allow to access to many functions of BaasBox server using a native interface.
One cool feature it is the “pass through” function that allow to perform a raw call to BaasBox in case you want to do something that is not supported by the SDK yet.
iOS SDK
The SDK is distributed in two ways:
- as a Cocoapod
- as a zip file
We recommend to install it using Cocoapods. Just add the following line to your Podfile.
pod 'BaasBoxSDK', '~> 0.9.0'
If you prefer the good old way, download the SDK from the download section of the website, and drag and drop the whole folder into your Xcode project.
Finally insert the following statement wherever you need BaasBox functionalities
#import "BAAClient.h"
and you are good to go.
Note for Swift projects. As of Xcode 6.1 you need to drag .h and .m files (and not the enclosing folder), otherwise you are not asked to create a bridging header.
Initialization
You need to initialize the SDK before making any API call. The best place to do it is in the `application:didFinishLaunchingWithOptions
method of your app. All you need to provide is the base URL and the app code, as in the example on the right.
1 2 | [BaasBox setBaseURL:@"http://localhost:9000" appCode:@"1234567890"]; |
1 | NOTHING HERE. See the 'iOS' Tab
|
1 | NOTHING HERE. See the 'iOS' Tab |
1 | NOTHING HERE. See the 'iOS' Tab |
Architecture and pass-through
The iOS SDK is structured following an onion-skin model. Most of the APIs are available through classes like BAAUser
or BAAObject
, which respectively contains methods for user management (login, signup, etc.) and documents (create, update, etc.). We suggest you use these methods when available. Should you see “TO BE IMPLEMENTED” in the iOS section, you can resort to use the BAAClient
class.
On the right there is an example of a GET request.
There are four methods, one for each HTTP verb.
- (void)getPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
- (void)postPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
- (void)putPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
- (void)deletePath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
As stated above, we strongly suggest you use higher level methods available in the classes BAAFile
, BAAObject
and BAAUser
and to resort to the BAAClient
methods only if you can’t do otherwise. We will soon finish the implementation of the SDK so that you won’t neeed to use BAAClient
methods at all in your app.
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assumes there is a logged in user BAAClient *client = [BAAClient sharedClient]; [client getPath:@"/file/details" parameters:parameters success:^(id responseObject) { NSLog(@"response is %@", responseObject); } failure:^(NSError *error) { NSLog(@"error is %@", error); }]; |
1 | NOTHING HERE. See the 'iOS' Tab
|
1 | NOTHING HERE. See the 'iOS' Tab |
1 | NOTHING HERE. See the 'iOS' Tab |
Android SDK
BaasBox provides a native Android SDK, to further ease development of mobile applications. The SDK is distributed as a jar. To get started download it from the download section of the website, and put it in the libs folder of your project. You can also use maven gradle or maven to depend on the library:
compile 'com.baasbox:baasbox-android:0.9.0'
Initialization
Currently, you can have only one client per application.
The client must be initialized before you can use any of the provided features.
The preferred way to initialize the SDK is to override the default
application and configure it in the onCreate()
method,
using the BaasBox.Builder
class.
Example initialization
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //... import com.baasbox.android.BaasBox; public class MyApp extends Application { private BaasBox client; @Override public void onCreate() { super.onCreate(); BaasBox.Builder b = new BaasBox.Builder(this); client = b.setApiDomain("address") .setAppCode("appcode") .setPushSenderIds("your google sender id") //used for push notifications .init(); } } |
1 | NOTHING HERE. See the 'Android' Tab |
1 | NOTHING HERE. See the 'Android' Tab
|
1 | NOTHING HERE. See the 'Android' Tab |
General usage
Most BaasBox REST resources are exposed through wrapper classes.
Endpoints are accessible through asynchronous methods, that accept a general callback interface
BaasHandler<T>
You can also access endpoints using synchronous alternatives using the *Sync
version of the methods.
Results are always wrapped in BaasResult<T>
, this can represent the actual result or a failure.
You can control asynchronous requests through the returned RequestToken.
Example requests
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Here BaasDocument is used as an example // it represents documents on the server, // more on this later // asynchronous request RequestToken tok = BaasDocument.fetchAll("coll", new BaasHandler<List<BaasDocument>>() { @Override public void handle(BaasResult<List<BaasDocument>> res) { // res is the result of the request } }); // synchronous equivalent BLOCKS!!! BaasResult<List<BaasDocument>> res = BaasDocument.fetchAllSync("coll"); |
1 | NOTHING HERE. See the 'Android' Tab |
1 | NOTHING HERE. See the 'Android' Tab
|
1 | NOTHING HERE. See the 'Android' Tab |
Asynchronous requests management
Asynchronous requests are executed by a pool of threads.
While an asynchronous request is running you can manage it
using the return value of the method, a RequestToken
.
Tokens are designed to let you suspend the assigned callback without
interrupting the real request, allowing the later resumption of
result processing on the main thread when you are ready to handle it.
This is quite useful when callbacks are tied to the lifecycle of your
acitivities.
Request tokens let you cancel/abort requests, or wait for their completion, this is useful in testing or if you want to parallelize your http requests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // an example asynchronous request in an activity public class MyActivity extends Activity implements BaasHandler<BaasUser>{ private final statis String BAAS_REQ = "tag"; private RequestToken token; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // you resume suspended requests // and obtain the token back token = RequestToken.loadAndResume( savedInstanceState, BAAS_REQ, this); if(token!=null){ // a request has been resumed } } public void onSaveInstanceSate(Bundle state){ super.onSaveInstanceState(state); if(token!=null){ token.suspendAndSave(state,TAG); } } public void handle(BaasResult<BaasUser> res){ token = null; // process result } } |
1 | NOTHING HERE. See the 'Android' Tab |
1 | NOTHING HERE. See the 'Android' Tab
|
1 | NOTHING HERE. See the 'Android' Tab |
Pass-through API
Some rest endpoints have no direct equivalent in the API.
For them you can use the lower level pass through API provided by the SDK
through the rest()
and restSync()
methods.
Whenever you see “TO BE IMPLEMENTED” in the Android section you can recur to this methods.
Using these methods you can access these APIs while still enjoying the rest
of the SDK features, such as concurrency and lifecycle management, caching,
handling of the authentication.
1 2 3 4 5 6 7 8 9 | BaasBox cli = BaasBox.getDefault(); cli.rest(HttpRequest.GET, "endpoint", optJsonBody, authenticate, new BaasHandler<JsonObject>(){ @Override public void handle(BaasResult<JsonObject> res){ }}); |
1 | NOTHING HERE. See the 'Android' Tab |
1 | NOTHING HERE. See the 'Android' Tab
|
1 | NOTHING HERE. See the 'Android' Tab |
JavaScript SDK
The JavaScript SDK is based on jQuery. The example page contains an example of each API call available.
Importing
You can download the SDK from the download page.
To use the SDK just import jQuery and the baasbox.js
in the head section of your page like this.
1 | NOTHING HERE. See the 'Javascript' Tab
|
1 | NOTHING HERE. See the 'Javascript' Tab |
1 | NOTHING HERE. See the 'Javascript' Tab |
1 2 3 4 5 6 7 8 9 10 11 12 | <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="baasbox.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { BaasBox.setEndPoint("http://localhost:9000"); //the address of your BaasBox server BaasBox.appcode = "1234567890"; //the application code of your server ... ... ... }; |
The jQuery cookie plugin, which you need to save authentication tokens, is already included at the top of the baasbox.js
file.
The SDK also supports Zepto.
Pass-through API
For any non-implemented API you can use the jQuery $.ajax interface.
API
General Remarks
These are the general notes about the REST API protocol used by BaasBox and its JSON format.
The response
Every response generated by BaasBox as a result of a REST call is a JSON object. In case of error, the data returned are more detailed and are useful to understand why the request was rejected.
Baasbox adds a “Date” header to every response reporting the date/time info, formatted using the RFC 1123 specification.
An example of a JSON response
1 2 3 4 5 | { "result": "ok|ko", "http_code": (200|201|204), "data": { } } |
An example of JSON error
1 2 3 4 5 6 7 8 9 | { "result": "error", "bb_code": <custom error code, if necessary>, "message": "a message explaining the problem in plain English", "resource": "the REST API called", "method": "the HTTP method used", "request_header": { ... the headers received by the server... }, "API_version": "...the BaasBox API version..." } |
Custom error codes
These are custom error codes specific to BaasBox, returned into the bb_code field.
- 40001: You are attempting to update a database object with older data. Version is not the same.
- 40002: The ACL field is not a valid JSON string.
- 40003: The specified permission is unknown. Valid ones are ‘read’, 'update’, 'delete’, 'all’.
- 40004: Only users and roles can be used.
- 40005: The specified user does not exist.
- 40006: The specified role does not exist.
- 40010: The JSON value must be an array.
- 40011: The body payload cannot be empty.
- 40101: Authentication info not valid or not provided. HINT: has your session expired?.
- 40020: The body payload doesn’t contain the 'message’ key or message value is NOT a String.
- 40021: Push profile invalid. It must be an Array of integer and accepted values are 1,2 or 3.
- 40022: Users MUST be an array of String.
- 40023: The body payload doesn’t contain key users.
- 40024: Sound value MUST be a String.
- 40025: Badge value MUST be a number.
- 40026: ActionLocalizedKey MUST be a String
- 40027: LocalizedKey MUST be a String.
- 40028: LocalizedArguments MUST be an Array of String.
- 40029: Collapse_key MUST be a String
- 40030: Time_to_live MUST be a positive number or equal zero.
- 40031: Message MUST be a String.
- 50301: Push settings are not properly configured. HINT: go to the administration console and check the settings.
- 50302: The server cannot resolve the host name. HINT: check your internet connection.
- 50303: Could not send push notifications. HINT: Check your API Key (Google).
- 50304: Could not save API KEY. HINT: Check your API Key, it’s possible that push service aren’t enabled in the Google Play Developer Console.
- 50305: Push app disabled, one or more app are disabled.
- 50306: Cannot switch, because settings for the selected mode are missing.
Pagination and query criteria
Some queries support pagination. There are two important parameters in paginated calls.
Parameter | Description |
---|---|
recordsPerPage | Number of elements to be retrieved per page. Optional |
skip | similar to the ‘skip’ keyword available for OrientDB queries, it allows to specify the number of records to be skipped before BaasBox starts collecting them as a result set. |
where | In order to search a condition, set a filter criteria in a SQL-like fashion (i.e.: “color=’yellow’ or address.city=’rome’” ). It is possible to use the positional mode, for example: “color=? or address.city=?” . In this case you must supply the parameters’ values using the params querystring parameter. |
params | an array of value for the where clause. For example: /API\_URL/WHERECLAUSE/¶ms=yellow¶ms=cyan |
orderBy | set an order by clause in a SQL-like fashion (i.e.: orderBy name desc). NOTE: the direction of ordering (asc or desc) is mandatory if pagination is used (see below) |
page | a 0 based index indicating the page requested |
fields | allows to specify a subset of fields (projections) to return instead of the entire record. It is also possibile to specify aggregate functions and execute all the operations allowed by OrientDB into the “select” statements. An exhaustive list of available functions is available at https://github.com/orientechnologies/orientdb/wiki/SQL-Where#wiki-field-operators, meanwhile the explanation of how to specify projections is at https://github.com/orientechnologies/orientdb/wiki/SQL-Query#projections |
groupBy | allows to indicate a “group by” criteria to group the result-set by one or more fields just like in standard SQL statements. This criteria is used in conjunction with the aggregate functions expressed into the “fields” |
count | if set to “true”, it returns the number of records that match the query instead of the entire record-set |
Example of valid calls:
/document/mycollection/count?where=color%3D’yellow’
/document/mycollection/count?where=color%3D%3F¶ms%3dyellow
/document/documents/count?where=color%3D%3F%20or%20color%3D%3F¶ms=yellow¶ms=cyan
Example of a paginated query
1 2 3 | curl 'http://localhost:9000/users?page=0&recordsPerPage=1' \ -H X-BB-SESSION:f083f676-65d0-45bd-bfe5-e876ef3f659e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | NSDictionary *parameters = @{kPageNumberKey : @0, kPageSizeKey : [NSNumber numberWithInteger:kPageLength]}; [BAAUser loadUsersWithParameters:parameters completion:^(NSArray *users, NSError *e) { if (error == nil) { NSLog(@"users are %@", users); } else { // deal with error } }]; // Apply a filter using the where keyword NSDictionary *parameters = @{@"where" : "color='red'"}; [Post getObjectsWithParams:parameters completion:^(NSArray *posts, NSError *error) { if (error == nil) { NSLog(@"Posts are %@", posts); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | Criteria paginate = BaasQuery.builder() .pagination(0,30) .orderBy("user.name") .criteria(); BaasUser.fetchAll(paginate,new BaasHandler<List<BaasUser>>() { @Override public void handle(BaasResult<List<BaasUser>> res) { if (res.isSuccess()) { for(BaasUser user:res.value()) { Log.d("LOG","User is: "+user); } } else { Log.e("LOG","error",res.error()); } } }); // aggregate operations and complex queries private static final BaasQuery PREPARED_QUERY = BaasQuery.builder() .collection("collection") .projection("field","aggreateOp") .where("condition") .whereParams("positionalParam","positionalParam2") .groupBy("field") .orderBy("field asc") .pagination(2,20) .build(); // then PREPARED_QUERY.query(new BaasHandler<List<JsonObject>>(){ @Override public void handle(BaasResult<List<JsonObjec>> res){ // handle result or failure } }); |
1 | NOTHING HERE |
User Management
Sign up
POST /user
Group: baasbox.account.create
Headers: See authorization header in the General Remarks
Description: This API allows a user to sign up to the App. Users will belong to the registered user role and they will post new content, will retrieve their own content, will change their password. BaasBox, since v.0.9.4, assigns a unique ID to each user. This ID can be used with the Link API.
You can force your own ID only via plugin script.
Please see the Plugin Users API documentation
Parameter | Description |
---|---|
username | The username for the user. Mandatory |
password | Password. Mandatory |
visibleByTheUser | an object whose fields are private and visible only by the user |
visibleByFriends | an object whose fields are visible by the user and friends (for friendship management) |
visibleByRegisteredUsers | an object whose fields are visible by the user, friends, any registered user |
visibleByAnonymousUsers | an object whose fields are public and visible by everyone, also anonymous users |
Sample request to create a user
1 2 3 4 | curl http://localhost:9000/user \ -d '{"username" : "cesare", "password" : "password"}' \ -H Content-type:application/json \ -H X-BAASBOX-APPCODE:1234567890 |
1 2 3 4 5 6 7 8 9 10 11 12 | BAAClient *client = [BAAClient sharedClient]; [client createUserWithUsername:@"cesare" password:@"password" completion:^(BOOL success, NSError *error) { if (success) { NSLog(@"user is %@", client.currentUser); } else { // display error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | BaasUser user = BaasUser.withUserName("andrea"); .setPassword("password"); JsonObject extras = user.getScope(Scope.PRIVATE) .putInt("age_info",27); user.signup(new BaasHandler<BaasUser>(){ @Override public void handle(BaasResult<BaasUser> result){ if(result.isSuccess()) { Log.d("LOG","Current user is: "+result.value()); } else { Log.e("LOG","Show error",result.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.signup("cesare", "password") .done(function (res) { console.log("signup ", res); }) .fail(function (error) { console.log("error ", error); }) |
Sample response when a user is created
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "result": "ok", "data": { "user": { "name": "cesare", "status": "ACTIVE", "roles": [{"name": "registered"}] }, "id": "6d5d8300-4339-40a5-8688-d1547fec6e05", "visibleByAnonymousUsers": { }, "visibleByTheUser": { }, "visibleByFriends": { }, "visibleByRegisteredUsers": { "_social": { } }, "signUpDate": "2015-06-16T16:20:32.032+0200", "generated_username": false, "X-BB-SESSION": "7f943d99-5872-4f0e-9865-a02386ef882b" }, "http_code": 201 } |
Here is the explanantion of the server response:
Field | Description |
---|---|
id | The unique ID associated with the user |
user.name | The username for the user. |
user.status | It is always ACTIVE. Users can be suspended by themselves or by an administrator |
visibleByTheUser | an object whose fields are private and visible only by the user |
visibleByFriends | an object whose fields are visible by the user and friends (for friendship management) |
visibleByFriends._social | If the user logged in with Facebook or another supported social network, here are some data that can be useful. For example the FBID. |
visibleByRegisteredUsers | an object whose fields are visible by the user, friends, any registered user |
signUpDate | The sign up date and time |
generated_username | When set to true indicates that the user.name field is a fake string generated by the system. This happens when the user logged in with a social network |
X-BB-SESSION | The session code that must be used in following calls |
Login
POST /login
Group: baasbox.account
Checks username/password and grants the user the right to execute other calls. This API returns a session token (X-BB-SESSION) that must be provided into all authenticated calls.
Parameter | Description |
---|---|
username | The username for the user. Mandatory |
password | Password. Mandatory |
appcode | The appcode of your server instance |
This API supports both application/x-www-form-urlencoded and application/json content types.
Sample request to login
1 2 3 4 | curl http://localhost:9000/login \ -d "username=cesare" \ -d "password=password" \ -d "appcode=1234567890" |
1 2 3 4 5 6 7 8 9 | [BAAUser loginWithUsername:@"cesare" password:@"password" completion:^(BOOL success, NSError *error) { if (success) { NSLog(@"user is %@", client.currentUser); } else { // show error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasUser user = BaasUser.withUserName("andrea") .setPassword("password"); user.login(new BaasHandler<BaasUser>() { @Override public void handle(BaasResult<BaasUser> result) { if(result.isSucces()) { Log.d("LOG", "The user is currently logged in: "+result.value()); } else { Log.e("LOG","Show error",result.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.login("cesare", "password") .done(function (user) { console.log("Logged in ", user); }) .fail(function (err) { console.log("error ", err); }) |
Sample response when a user is logged in
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "result": "ok", "data": { "user": { "name": "cesare", "status": "ACTIVE", "roles": [{"name": "registered"}] }, "id": "6d5d8300-4339-40a5-8688-d1547fec6e05", "visibleByAnonymousUsers": { }, "visibleByTheUser": { }, "visibleByFriends": { }, "visibleByRegisteredUsers": { "_social": { } }, "signUpDate": "2015-06-16T16:20:32.032+0200", "generated_username": false, "X-BB-SESSION": "7f943d99-5872-4f0e-9865-a02386ef882b" }, "http_code": 201 } |
Here is the explanantion of the server response:
Field | Description |
---|---|
id | The unique ID associated with the user |
user.name | The username for the user. |
user.status | It is always ACTIVE. Users can be suspended by themselves or by an administrator |
visibleByTheUser | an object whose fields are private and visible only by the user |
visibleByFriends | an object whose fields are visible by the user and friends (for friendship management) |
visibleByFriends._social | If the user logged in with Facebook or another supported social network, here are some data that can be useful. For example the FBID. |
visibleByRegisteredUsers | an object whose fields are visible by the user, friends, any registered user |
signUpDate | The sign up date and time |
generated_username | When set to true indicates that the user.name field is a fake string generated by the system. This happens when the user logged in with a social network |
X-BB-SESSION | The session code that must be used in following calls |
Logout
POST /logout[/:pushToken]
Group: baasbox.account
Allows a user to logout from the app on a specific device. A push notification will not be sent to the user through the specified device.
Parameter | Description |
---|---|
pushToken | Optional. The push notification token that you have used to activate push notifications. |
Example of a logout request
1 2 | curl -X POST http://localhost:9000/logout \
-H X-BB-SESSION:da506029-4512-45a9-9606-43fcdda4121a -H X-BAASBOX-APPCODE:1234567890
|
1 2 3 4 5 6 7 8 9 | [BAAUser logoutWithCompletion:^(BOOL success, NSError *error) { if (success) { // user logged out } else { // error logging out } }]; |
1 2 3 4 5 6 7 8 9 10 | BaasUser.current().logout(new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> result) { if(result.isSuccess()) { Log.d("LOG", "Logged out: "+(BaasUser.current() == null)); } else{ Log.e("LOG","Show error",result.error()); } }; }); |
1 2 3 4 5 6 7 | BaasBox.logout() .done(function (res) { console.log(res); }) .fail(function (error) { console.log("error ", error); }) |
Sample response when a user logs out
1 2 3 4 5 | { "result":"ok", "data":"user logged out", "http_code":200 } |
Suspend a user
Suspends a given user.
Only administrators can call this API.
PUT /me/suspend
1 2 3 | curl -X PUT http://localhost:9000/me/suspend \ -H X-BB-SESSION:da506029-4512-45a9-9606-43fcdda4341a \ -H X-BAASBOX-APPCODE:1234567890 |
Allows a user to suspend their account.
Only administators can reactivate it.
PUT /admin/user/suspend/:username
1 2 3 | curl -X PUT http://localhost:9000/admin/user/suspend/user1 \ -H X-BB-SESSION:da506029-4512-45a9-9606-43fcdda4121a \ -H X-BAASBOX-APPCODE:1234567890 |
Reactivate a user
PUT /admin/user/activate/:username
1 2 3 | curl -X PUT http://localhost:9000/admin/user/activate/user1 \ -H X-BB-SESSION:da506029-4512-45a9-9606-43fcdda4121a \ -H X-BAASBOX-APPCODE:1234567890 |
Reactivate a previoulsy suspended user.
Only administrators can call this API.
Logged user profile
GET /me
Group: baasbox.account
Retrieves details about the logged in user.
Request to fetch the currently logged in user profile
1 2 | curl http://localhost:9000/me \
-H X-BB-SESSION:196f48ed-6154-4b49-8dc6-8b9b2ce4900a
|
1 2 3 4 5 6 7 8 9 | [BAAUser loadCurrentUserWithCompletion:^(BAAUser *user, NSError *error) { if (error == nil) { // deal with user object } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasUser.current().refresh(new BaasHandler<BaasUser>() { @Override public void handle(BaasResult<BaasUser> result) { if(result.isSuccess()) { BaasUser user = result.value(); JsonObject data = user.getScope(Scope.PRIVATE); Log.d("LOG","Log some private data: "+data); } else { Log.e("LOG","error:",result.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.fetchCurrentUser() .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Sample response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "result": "ok", "data": { "user": { "name": "cesare", "status": "ACTIVE", "roles": [{"name": "registered"}] }, "id": "6d5d8300-4339-40a5-8688-d1547fec6e05", "visibleByAnonymousUsers": { }, "visibleByTheUser": { }, "visibleByFriends": { }, "visibleByRegisteredUsers": { "_social": { } }, "signUpDate": "2015-06-16T16:20:32.032+0200", "generated_username": false, "X-BB-SESSION": "7f943d99-5872-4f0e-9865-a02386ef882b" }, "http_code": 201 } |
Update user profile
PUT /me
Group: baasbox.account
Updates details about the logged in user.
The body payload to be sent has the following form:
{
"visibleByTheUser": {},
"visibleByFriends": {},
"visibleByRegisteredUsers": {},
"visibleByAnonymousUsers": {}
}
All four properties are optional. You can send just one of them or all four. See example on the right. The values for this fields can be anything you like: string, numbers, arrays or JSON encoded objects.
Parameter | Description |
---|---|
visibleByTheUser | fields are private and visible only by the user |
visibleByFriends | fields are visible by the user and friends |
visibleByRegisteredUsers | fields are visible by the user, friends and any registered user |
visibleByAnonymousUsers | fields are public and visible by everyone, even anonymous users |
PUT request to update the logged in user profile
1 2 3 4 | curl -X PUT http://localhost:9000/me \ -d '{"visibleByFriends" : {"phoneNumber" : "+1123456"}}' \ -H Content-type:application/json \ -H X-BB-SESSION:a30e8f43-4d90-4324-91d2-6065fa6ca63c |
1 2 3 4 5 6 7 8 9 10 11 | BAAUser *user = ... ; // some user [user.visibleByAnonymousUsers setObject:@"mail@mail.com" forKey:@"email"]; [user updateWithCompletion:^(BAAUser *user, NSError *error) { if (error == nil) { NSLog(@"user is %@", [user jsonString]); } else { NSLog(@"error %@", error); } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasUser user = BaasUser.current(); user.getScope(Scope.PRIVATE).putString("property","value"); user.save(new BaasHandler<BaasUser>() { @Override public void handle(BaasResult<BaasUser> res) { if(res.isSuccess()) { Log.d("LOG", "User data has been saved"); } else { Log.e("LOG", error,res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.updateUserProfile({"visibleByAnonymousUsers": {"email" : "mail@mail.com"}}) .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Sample JSON response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | { "result": "ok", "data": { "user": { "name": "cesare", "status": "ACTIVE", "roles": [ { "name": "registered" } ] }, "signUpDate": "2014-01-24T11:28:09.009+0100", "visibleByFriends": { "phoneNumber": "+1123456" } }, "http_code": 200 } |
Fetch a user profile
GET /user/:username
Group: baasbox.users
Allows to retrieve information about a user profile.
Parameter | Description |
---|---|
username | Username of the user. Mandatory. |
Example of a request to get a user profile
1 2 | curl http://localhost:9000/user/cesare \
-H X-BB-SESSION:f083f676-65d0-45bd-bfe5-e876ef3f659e
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [BAAUser loadUserDetails:@"cesare" completion:^(BAAUser *user, NSError *error) { if (error == nil) { NSLog(@"user details are %@", user); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 | BaasUser.fetch("a",new BaasHandler<BaasUser>() { @Override public void handle(BaasResult<BaasUser> res) { if(res.isSuccess()){ BaasUser user = res.value(); Log.d("LOG","The user: "+user); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.fetchUserProfile("cesare") .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | { "result": "ok", "data": { "user": { "name": "a", "status": "ACTIVE", "visibleByFriends": {"phoneNumber":"+1985478562"}}, "roles": [ { "name": "registered" } ] }, "signUpDate": "2014-01-24T12:13:08.008+0100" } |
Fetch users
GET /users
Group: baasbox.users
Allows to retrieve a list of users. This API supports pagination and query criteria.
Example of a request to get the users list
1 2 | curl http://localhost:9000/users \
-H X-BB-SESSION:f083f676-65d0-45bd-bfe5-e876ef3f659e
|
1 2 3 4 5 6 7 8 9 10 11 12 | NSDictionary *parameters = @{kPageNumberKey : @0, kPageSizeKey : [NSNumber numberWithInteger:kPageLength]}; [BAAUser loadUsersWithParameters:parameters completion:^(NSArray *users, NSError *error) { if (error == nil) { NSLog(@"users are %@", users); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | Criteria filter = BaasQuery.builder() .pagination(0,2) .orderBy("user.name") .criteria(); BaasUser.fetchAll(filter,new BaasHandler<List<BaasUser>>() { @Override public void handle(BaasResult<List<BaasUser>> res) { if(res.isSuccess()) { for(BaasUser u: res.value()) { Log.d("LOG", "The user is: "+u.getName()); } } else { Log.e("LOG","error"); } } }); |
1 2 3 4 5 6 7 | BaasBox.fetchUsers() .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | { "result": "ok", "data": [ { "user": { "roles": [ { "name": "registered" } ], "name": "cesare", "status": "ACTIVE" }, "signUpDate": "2014-01-24T11:28:09.009+0100", "visibleByTheUser": { "email": "cesare@email.com" }, "visibleByFriends": { "phoneNumber": "+1123456" } }, { "user": { "roles": [ { "name": "registered" } ], "name": "e", "status": "ACTIVE" }, "signUpDate": "2014-01-24T12:10:37.037+0100" } ], "http_code": 200 } |
Change password
PUT /me/password
Group: baasbox.account
To change the password of the logged in user.
Parameter | Description |
---|---|
old | The old password. Mandatory. |
new | The new password. Mandatory. |
Example of request
1 2 3 4 | curl -X PUT http://localhost:9000/me/password \ -d '{"old" : "oldpass", "new" : "newpass"}' \ -H Content-type:application/json \ -H X-BB-SESSION:a30e8f43-4d90-4324-91d2-6065fa6ca63c |
1 2 3 4 5 6 7 8 9 10 11 12 | BAAUser *user = ...; // Some user [user changeOldPassword:@"oldpass" toNewPassword:@"newpass" completionBlock:^(BOOL success, NSError *error) { if (success) { NSLog(@"pass updared"); } else { NSLog(@"err %@", error); } }]; |
1 2 3 4 5 6 7 8 9 10 | BaasUser current = BaasUser.current(); current.changePassword("newpassword",new BaasHandler<Void>() { public Void handle(BaasHandler<Void> res) { if(res.isSuccess()) { Log.d("LOG", "New password updated, you should relogin"); } else { Log.e("LOG","error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.changePassword("oldpass", "newpass") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Change username
PUT /me/username
Group: baasbox.users
Headers: See authorization header in the General Remarks
Description: Starting from v. 0.9.0 it is possibile to change usernames
Parameter | Description |
---|---|
username | The new username |
Example of a request
1 2 3 4 | curl -X PUT http://localhost:9000/me/username \ -d '{"username" : "matteo"}' \ -H Content-type:application/json \ -H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23 |
1 2 | //Please see the "pass-through" functionality of the iOS SDK
|
1 2 | //Please see the "pass-through" functionality of the Android SDK
|
1 2 | //Please see the "pass-through" functionality of the JS SDK
|
Example of a response
1 2 3 4 5 6 | { "result": "ok", "data": "", "http_code": 200 } |
Password reset
(Forgotten password workflow)
GET /user/:username/password/reset
Group: baasbox.account.lost_password
Allows to reset a user’s password. This API is useful when users forget their password and need to reset it. This is the workflow:
- the server checks if the email address exists within the
visibleByTheUser
fields in the user profile - the server sends an email to that address with a generated link to follow in order to reset the password
- the user opens the email and opens the given link in a web browser. That will show a form with two html password fields
- the user fills in the two fields and submits the form
- a confirmation message is shown by the server
- the settings (SMTP configuration, email message to be sent, html form, confirmation and error web page) can be set up by the administrator via the Settings menu in the admin console
Parameter | Description |
---|---|
username | Username of the user who wants to reset the password. Mandatory. |
Example of a request for password reset
1 2 | curl http://localhost:9000/user/cesare/password/reset \
-H X-BAASBOX-APPCODE:1234567890
|
1 2 3 4 5 6 7 8 9 10 | BAAUser *user = ... ; // Some user [user resetPasswordWithCompletion:^(BOOL success, NSError *error) { if (success) { NSLog(@"password reset OK"); } else { NSLog(@"error %@", error); } }]; |
1 2 3 4 5 6 7 8 9 10 | BaasUser.requestPasswordReset("cesare",new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res) { if(res.isSuccess()) { Log.d("LOG","Password reset has been requested"); } else{ Log.e("LOG","Error",res.error()); } } }; |
1 2 3 4 5 6 7 | BaasBox.resetPassword() .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of an error
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { "result": "error", "message": "Cannot reset password, the \"email\" attribute is not defined into the user's private profile", "resource": "/user/cesare/password/reset", "method": "GET", "request_header": { "Accept": [ "*/*" ], "Host": [ "localhost:9000" ], "X-BAASBOX-APPCODE": [ "1234567890" ] }, "API_version": "<BaasBox version>" } |
Social Login
BaasBox provides an API that allows you to connect/create your users through social networks.
BaasBox social API is integrated with the following social networks: - Facebook - Google +
We are planning on adding more in the near future.
The use of an API in a client application needs an appKey and an appSecret usually provided by the social network itself. More information on how you can get those values can be found here:
- facebook (http://developers.facebook.com/docs/)
- google+ (http://code.google.com/apis/console)
Once you create your app inside the social network you will have access to the apiKey / apiSecret values; those values must be stored into the BaasBox database in order to use the BaasBox social feature: you can access the social login tab from the settings menu in the admin console.
Then click on the specific social network you are working on, fill in the form with the keys and press Save. You can disable the social feature for a specific social network by pressing the disable xxx button
Once you have connected to a social network you can use any client library to obtain the OAuth tokens for users account, and store them with the social API provided by BaasBox.
You can find an application example and tutorial here
API documentation
Retrieve all social network connections for a connected user
GET /social
Headers:
- X-BAASBOX-APPCODE: App Code
- X-BB-SESSION: Session token for current user
Returns a JSON representation of the social network connected to the user along with all the information retrieved at the moment of login/linking. An example of the returned data is:
Example of a request
1 2 | curl http://localhost:9000/social \
-H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Assumes a user is logged in BAAClient *client = [BAAClient sharedClient]; [client.currentUser fetchLinkedSocialNetworksWithCompletion:^(NSArray *objects, NSError *error) { if (error == nil) { NSLog(@"social are %@", objects); } else { NSLog(@"%@", error); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | "data": [ { "username": "xxx", "password": null, "from": "google", "token": "<token>", "secret": "<secret>", "id": "<userid>", "additionalData": { "email": "<email>", "name": "<name>", "avatarUrl": "<avatar>", "personal_url": "<personal_url>" } } ] |
This API should be invoked with a valid X-BB-SESSION header and a valid X-BAASBOX-APPCODE header as specified in the authorization section of the doc.
This method can be used to retrieve the tokens to post on the social network wall using a client SDK provided by the social network itself.
Returns:
- 200 code with a JSON object whose data property contains all the social networks linked to the current user.
- 404 code if the user does not have any social network linked to their account
- 401 code (Unauthorized) if one of the mandatory headers are missing
Login a User with a specified social network
POST /social/:socialNetwork
Headers: X-BAASBOX-APPCODE = App code
URL parameters
:socialNetwork could be facebook or google
Parameters:
oauth_token: the oauth_token obtained after user authentication and authorization with a client library (see example here)
oauth_secret: the oauth_secret obtained after user authentication and authorization with a client library (see example here)
This method allows to login into the BaasBox app using the tokens obtained by a social network client library. If the user has already logged in with the same tokens the server will simply return the X-BB-SESSION token that will be used for further requests.
If the user does not exist it will be created and an X-BB-SESSION token will be returned. Upon user creation some data will be extracted from the social network profile and they will be stored inside the user object. A username will be uniquely generated (to prevent username collision). Therefore after a succesful login, if necessary, the client app may ask for a username and update the user object accordingly.(See the example here)
Returns:
- 200 code with the user’s X-BB-SESSION token
- 400 code if one of the oauth_token or oauth_secret was missing
- 401 code if the X-BAASBOX-APPCODE header was missing
- 500 code if something on the server went wrong (i.e. another user with the same tokens already exists)
Example of a request to login with Facebook
1 2 3 4 | curl -X POST http://localhost:9000/social/facebook \ -d "oauth_token=OAUTH_TOKEN" \ -d "oauth_secret=OAUTH_SECRET" \ -H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | NSString *token = ... ; // Valid authentication token obtained by Facebook. [BAAUser loginWithFacebookToken:token completion:^(BOOL success, NSError *error) { if (success) { BAAClient *c = [BAAClient sharedClient]; NSLog(@"logged in with facebook %@", c.currentUser); } else { NSLog(@"error %@", error); } }]; |
1 2 3 4 5 6 7 8 | String token= ...;// a valid token from the provider BaasUser.signupWithProvider(Social.FACEBOOK,token,token,new BaasHandler<BaasUser>(){ @Override public void handler(BaasResult<BaasUser> res) { if(res.isSuccess()){ BaasUser current = res.value(); } }); |
1 | TO BE IMPLEMENTED |
Example of a request to login with Google
1 2 3 4 | curl -X POST http://localhost:9000/social/google \ -d "oauth_token=OAUTH_TOKEN" \ -d "oauth_secret=OAUTH_SECRET" \ -H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | NSString *token = ... ; // Valid authentication token obtained by Google. [BAAUser loginWithGoogleToken:token completion:^(BOOL success, NSError *error) { if (success) { BAAClient *c = [BAAClient sharedClient]; NSLog(@"logged in with facebook %@", c.currentUser); } else { NSLog(@"error %@", error); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Link a user to a specified social network
PUT /social/:socialNetwork
Headers:
- X-BAASBOX-APPCODE = App code
- X-BB-SESSION = Session token for the current user
URL parameters
:socialNetwork could be facebook or google
Parameters: oauth_token: the oauth_token obtained after user authentication and authorization with a client library (see example here)
oauth_secret: the oauth_secret obtained after user authentication and authorization with a client library (see example here)
This method allows an existing user to connect their account to a specified social network.
This procedure is very similar to the Login method with a difference: this is a PUT request and it must be invoked with the X-BB-SESSION header.
Returns: - 200 code with an empty response if the linking was succesful, - 401 code if any of the mandatory headers was missing, - 500 code if something on the server went wrong (i.e. another user with the same tokens already exists)
Example of a request to link an account to Facebook
1 2 3 4 | curl -X PUT http://localhost:9000/social/facebook \ -d "oauth_token=OAUTH_TOKEN" \ -d "oauth_secret=OAUTH_SECRET" \ -H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assumes a user is already logged in NSString *token = ...; // Token obtained by Facebook BAAClient *client = [BAAClient sharedClient]; [client.currentUser linkToFacebookWithToken:token completion:^(BOOL success, NSError *error) { if (success) { NSLog(@"user linked to FB"); } else { NSLog(@"error %@", error); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a request to link an account to Google
1 2 3 4 | curl -X PUT http://localhost:9000/social/google \ -d "oauth_token=OAUTH_TOKEN" \ -d "oauth_secret=OAUTH_SECRET" \ -H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assumes a user is already logged in NSString *token = ...; // Token obtained by Google BAAClient *client = [BAAClient sharedClient]; [client.currentUser linkToGoogleWithToken:token completion:^(BOOL success, NSError *error) { if (success) { NSLog(@"user linked to FB"); } else { NSLog(@"error %@", error); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Unlink a user from a specified social network
DELETE /social/:socialNetwork
Headers:
- X-BAASBOX-APPCODE = App code
- X-BB-SESSION = Session token for current user
URL parameters: socialNetwork could be facebook or google
This method unlinks the current user account from a specified social network. If the user was generated by a social network login and the specified social network is the only one linked to the user, an error will be raised (as the user will not be available to connect anymore).
Example of a request to unlink an account from Facebook
1 2 | curl -X DELETE http://localhost:9000/social/facebook \
-H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23
|
1 2 3 4 5 6 7 8 9 10 11 | // Assumes a user is already logged in BAAClient *client = [BAAClient sharedClient]; [client.currentUser unlinkFromFacebookWithCompletion:^(BOOL success, NSError *error) { if (success) { NSLog(@"account unlinked"); } else { NSLog(@"error %@", error); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a request to unlink an account from Google
1 2 | curl -X DELETE http://localhost:9000/social/google \
-H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23
|
1 2 3 4 5 6 7 8 9 10 11 | // Assumes a user is already logged in BAAClient *client = [BAAClient sharedClient]; [client.currentUser unlinkFromGoogleWithCompletion:^(BOOL success, NSError *error) { if (success) { NSLog(@"account unlinked"); } else { NSLog(@"error %@", error); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Friendship and Social API
BaasBox is able to manage relations among users, implementing a concept of friendship similar (but not identical) to the one used by Twitter. A user registered on BaasBox can “follow” another user calling the follow API.
What happens is that such user is added to a special role called friends_of_<followed user>.
For example, let’s say we have three users: user_a, user_b, user_c. user_b and user_c decide to follow user_a, and therefore, each of them with their own credentials will call the API follow_:
PUT /follow/user_a
now user_b_ and user_c belong to the group friends_ofuser_a_.
When user_a wants to share something with his followers, he just has to grant reading access to his content to users belonging to the role friends_ofuser_a_.
For example, supposing that there is a defined collection called posts, and that user_a had created in it a document with id aaa-bbb-ccc-ddd.
user_a in order to share this document with his friends has to call the grant API:
PUT /document/posts/aaa-bbb-ccc-ddd/read/role/friends_of_user_a
Now everytime user_b or user_c query for posts they will see the _user_a aaa-bbb-ccc-ddd document as well.
To revoke such grant, and therefore not to share the content any longer:
DELETE /document/posts/aaa-bbb-ccc-ddd/read/role/friends_of_user_a
Finally, if user_b doesn’t want to follow user_a anymore, he can invoke the unfollow API:
DELETE /follow/user_a
Please note that the follow API is not mutual, just like in Twitter.
Follow a user
POST /follow/:username
Group: baasbox.friendship.create
This API allows a user to follow another user. Once the relation is established
the follower will be able to see the documents and files created by the followed
user as well as its visibleByFriends
data in the user profile.
Parameter | Description |
---|---|
username | Username of the user to be followed. Mandatory. |
Example of a request to follow the user “cesare”
1 2 | curl -X POST http://localhost:9000/follow/cesare \
-H X-BB-SESSION:c6fb7001-ccb5-4048-8935-80ef197e1390
|
1 2 3 4 5 6 7 8 9 10 11 12 | BAAUser *user = ...; // Instance of user to be followed [BAAUser followUser:user completion:^(BAAUser *user, NSError *error) { if (error == nil) { NSLog(@"now following user %@", user); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 | BaasUser user = BaasUser.withUsername("cesare"); user.follow(new BaasHandler<BaasUser>() { @Override public void handle(BaasResult<BaasUser> res) { if(res.isSuccess()) { JsonObject profile = res.value().getScope(Scope.FRIEND); Log.d("LOG", "It's profile "+profile); } else{ // there was an error } } }); |
1 2 3 4 5 6 7 | BaasBox.followUser("cesare") .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | { "result": "ok", "data": { "user": { "name": "cesare", "roles": [ { "name": "registered" }, { "name": "friends_of_cesare" } ], "status": "ACTIVE" }, "signUpDate": "2014-01-24T11:28:09.009+0100", "visibleByFriends": { "phoneNumber": "+1123456" } }, "http_code": 201 } |
Unfollow a user
DELETE /follow/:username
Group: baasbox.friendship.create
This API allows a user to unfollow another user. Once the relation has been deleted, the user won’t be able to see the documents and files created by the unfollowed user anymore.
Parameter | Description |
---|---|
username | Username of the user to be unfollowed. Mandatory. |
Example of an unfollow request
1 2 | curl -X DELETE http://localhost:9000/follow/cesare \
-H X-BB-SESSION:c6fb7001-ccb5-4048-8935-80ef197e1390
|
1 2 3 4 5 6 7 8 9 10 11 12 | BAAUser *user = ...; // Instance of user to be unfollowed [BAAUser unfollowUser:user completion:^(BAAUser *user, NSError *error) { if (error == nil) { NSLog(@"not following anymore user %@", user); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasUser.withUserName("cesare").unfollow( new BaasHandler<BaasUser>() { @Override public void handle(BaasResult<BaasUser> res) { if(res.isSuccess()) { JsonObject data = res.value().getScope(Scope.FRIEND); Log.d("LOG", "No more friend data:"+(data==null)); } else { // there was an error } } }); |
1 2 3 4 5 6 7 | BaasBox.unfollowUser("cesare") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Fetch following
GET /following/:username
Group: baasbox.friendship
This API returns a list of users who are followed by the user with username
passed as a parameter. If no username is provided, the API returns all users followed by the logged in user. In its data
property the method returns an array filled with the user profiles representing their “friends”. Each profile will contain the visibleByFriends
data which would otherwise be hidden.
Parameter | Description |
---|---|
username | Username of the user whose following list has to be fetched. Optional. |
Example of a request to fetch who “cesare” is following
1 2 | curl http://localhost:9000/following/cesare \
-H X-BB-SESSION:c6fb7001-ccb5-4048-8935-80ef197e1390
|
1 2 3 4 5 6 7 8 9 | BAAUser *user = ... // user representing "cesare" [user loadFollowingWithCompletion:^(NSArray *following, NSError *error) { for (BAAUser *u in following) { NSLog("cesare is following %@", u) } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasUser user = ... // the user representing "cesare" user.following(new BaasHandler<List<BaasUser>>() { @Override public void handle(BaasResult<List<BaasUser>> res) { if(res.isSuccess()){ for(BaasUser u: res.value()) { Log.d("LOG","Cesare is follwing: "+u.getName()); } } } }); |
1 2 3 4 5 6 7 | BaasBox.fetchFollowing("cesare") .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { "result": "ok", "data": [ { "user": { "roles": [ { "name": "registered" } ], "name": "a", "status": "ACTIVE" }, "signUpDate": "2014-01-24T12:13:08.008+0100" } ], "http_code": 200 } |
Fetch followers
GET /followers/:username
Group: baasbox.friendship
This API returns the list of followers for the user with username
specified in the parameter. If no username
is provided the API returns the list of followers for the currently logged in user. The method returns in its data
property an array filled with the user profiles representing their “friends”. Each profile will contain the visibleByFriends
data which would otherwise be protected.
Parameter | Description |
---|---|
username | Username of the user whose followers list has to be fetched. Optional. |
Example of a request to fetch “cesare”’s followers
1 2 | curl http://localhost:9000/followers/cesare \
-H X-BB-SESSION:c6fb7001-ccb5-4048-8935-80ef197e1390
|
1 2 3 4 5 6 7 8 9 | BAAUser *user = ... // user representing "cesare" [user loadFollowersWithCompletion:^(NSArray *following, NSError *error) { for (BAAUser *u in following) { NSLog("%@ is following cesare", u) } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasUser user = ... // the user representing "cesare" user.followers(new BaasHandler<List<BaasUser>>() { @Override public void handle(BaasResult<List<BaasUser>> res) { if(res.isSuccess()){ for(BaasUser u: res.value()) { Log.d("LOG", u.getName()+ " is following cesare"); } } } }); |
1 2 3 4 5 6 7 | BaasBox.fetchFollowers("cesare") .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response with “cesare”’s followers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { "result": "ok", "data": [ { "user": { "roles": [ { "name": "registered" } ], "name": "a", "status": "ACTIVE" }, "signUpDate": "2014-01-24T12:13:08.008+0100" } ], "http_code": 200 } |
Push Notifications
Push notifications are messages that a user can receive using an APP that has BaasBox as back-end. Supported platforms are Android and iOS. Certificates have to be configured in the Settings of the console.
Enable push notifications
PUT /push/enable/:os/:pushToken
Group: baasbox.notifications.receive
Enables a specific user (logged using a specific device) to receive push notifications.
Parameter | Description |
---|---|
os | The operative system. One of: ios , android . Mandatory. |
pushToken | The token returned by either Apple or Google to enable push notifications. Mandatory. |
Example of a request to enable push notifications
1 2 | curl -X PUT http://localhost:9000/push/enable/ios/123 \
-H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Call this method only AFTER a successful login or signup. BAAClient *client = [BAAClient sharedClient]; [client askToEnablePushNotifications]; // implement these delegate methods in the app delegate. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { BAAClient *client = [BAAClient sharedClient]; [client enablePushNotifications:deviceToken completion:^(BOOL success, NSError *error) { if (error) { // handle the error } }]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { // handle the error } |
1 2 3 4 5 6 7 8 9 10 11 | // given you have provided one or more sender ids to the initial configuration BaasCloudMessagingService box=BaasBox.messagingService(); box.enable(new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res){ if(res.isSuccess()){ // registrationid saved on the server } } }); |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Disable push notifications
PUT /push/disable/:pushToken
Group: baasbox.notifications.receive
Disable a specific user (logged using a specific device) to unreceive push notifications.
Parameter | Description |
---|---|
pushToken | The token returned by either Apple or Google to disable push notifications. Mandatory. |
Example of a request to disable push notifications
1 2 | curl -X PUT http://localhost:9000/push/disable/123 \
-H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23
|
1 2 3 4 5 6 7 8 9 10 11 | // Assumes there is a logged in user BAAClient *client = [BAAClient sharedClient]; [client disablePushNotificationsWithCompletion:^(BOOL success, NSError *error) { if (success) { NSLog(@"push notifications disabled"); } else { NSLog(@"error %@", error); } }]; |
1 2 3 4 5 6 7 8 9 | BaasCloudMessagingService client = BaasBox.messagingService(); client.disable(new BaasHandler<Void>(){ @Override public void handle(BaasResult<Void> res){ if(res.isSuccess()){ // successfully unregistered } } }); |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Send a push notification
For information about additional data check the following links
POST /push/message/
Group: baasbox.notifications.send
Allows to send a push notification. This will be sent to every device, registered with the respective app, on which users have enabled push notifications.
Parameter | Description | Type |
---|---|---|
message | The message for the users. Mandatory. | String |
users | The username of the users who have to receive the notification. Mandatory | Array of String |
profiles | The app used for sending push notifications (only allow Array of Integer i.e. [1,2,3]). If empty, app #1 will be used | Array of Integer |
sound | A sound to play for iOS | String |
badge | The number to display as the badge of the application icon for iOS | Integer |
actionLocalizedKey | The string is used as a key to get a localized string in the current localization to be used for the right button’s title instead of “View” for iOS | String |
localizedKey | A key to an alert-message string in a Localizable.strings file for the current localization for iOS | String |
localizedArguments | Variable string values to appear in place of the format specifiers in localizedKey for iOS | Array of String |
custom | Custom data Android & iOS | Value, JSONArray or JSONObject |
collapse_key | An arbitrary string (such as “Updates Available”) that is used to collapse a group of like messages when the device is offline for Android | String |
time_to_live | How long (in seconds) the message should be kept on the GCM storage if the device is offline for Android. If empty, it will be set to 4 weeks | Integer, max value allow 2419200 |
content-available | (Available from BaasBox 0.9.0) Provide this key with a value of 1 to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed for iOS 7 | Integer |
category | (Available from BaasBox 0.9.0) Sets the category of the notification for iOS8 notification actions | String |
Example of a request to send a push notification
1 2 3 4 | curl -X POST http://localhost:9000/push/message \ -d '{"message" : "hi", "users" : ["cesare"]}' \ -H Content-type:application/json \ -H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | BAAClient *client = [BAAClient sharedClient]; [client postPath:@"/push/message" parameters:@{@"message" : @"hi", @"users" : @[@"cesare"]} success:^(id responseObject) { NSLog(@"Notification sent"); } failure:^(NSError *error) { NSLog(@"error %@", error); }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasBox.messagingService() .newMessage() .profiles(BaasCloudMessagingService.PROFILE2) .extra(new JsonObject().put("key","value")) .text("message") .to(user,user2) .send(new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> result) { // handle the result } }); |
1 2 3 4 5 6 7 | BaasBox.sendPushNotification({"message" : "hi", "users" : ["cesare"]}) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | { "message":"test". "profiles":[1], "sound":"sound.wav", "actionLocalizedKey":"Play", "localizedKey":"GAME_PLAY_REQUEST_FORMAT", "localizedArguments":["Jenna","Frank"], "badge":10, "custom": { "data": "text", "title": "Titletext", }, "category":"invite", "collapse_key":"update_match_15", "time_to_live":106, "users":["X","Y","Z"] } |
Following an example for the content-available field (available since iOS 7.0)
Example of a request for content-available field
1 2 3 4 5 | { "message":"test", "profiles":[1], "content-available":1 } |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // if all OK { "result": "ok", "data": "", "http_code": 200 } //or (in case of errors in settings i.e. push sent to Android & iOS devices but only Android settings are configured) { "result": "ok", "data": "Push notifications were sent but they may be subject to loss of data. HINT: check push settings in console", "http_code": 200, "bb_code": "20001" } |
DEPRECATED
POST /push/message/:username
Group: baasbox.notifications.send
Allows to send a push notification. This will be sent to every device, registered with the respective app, on which the user has enabled push notifications.
Parameter | Description | Type |
---|---|---|
message | The message for the user. Mandatory. | String |
username | The username of the user who has to receive the notification. Mandatory. | |
profiles | The app used for sending push notifications (only allow Array of Integer i.e. [1,2,3]). If empty, app #1 will be used | Array of Integer |
sound | A sound to play for iOS | String |
badge | The number to display as the badge of the application icon for iOS | Integer |
actionLocalizedKey | The string is used as a key to get a localized string in the current localization to be used for the right button’s title instead of “View” for iOS | String |
localizedKey | A key to an alert-message string in a Localizable.strings file for the current localization for iOS | String |
localizedArguments | Variable string values to appear in place of the format specifiers in localizedKey for iOS | Array of String |
custom | Custom data Android & iOS | Value, JSONArray or JSONObject |
collapse_key | An arbitrary string (such as “Updates Available”) that is used to collapse a group of like messages when the device is offline for Android | String |
time_to_live | How long (in seconds) the message should be kept on the GCM storage if the device is offline for Android. If empty, it will be set to 4 weeks | Integer, max value allowed 2419200 |
content-available | (Available from BaasBox 0.9.0) Provide this key with a value of 1 to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed for iOS 7 | Integer |
category | (Available from BaasBox 0.9.0) Sets the category of the notification for iOS8 notification actions | String |
1 2 3 4 | curl -X POST http://localhost:9000/push/message/cesare \ -d '{"message" : "hi"}' \ -H Content-type:application/json \ -H X-BB-SESSION:2605d809-03f0-4751-8f8e-5f658e179a23 |
1 2 3 4 5 6 7 8 9 10 11 12 | BAAClient *client = [BAAClient sharedClient]; [client postPath:@"/push/message/cesare" parameters:@{@"message" : @"Hi there"} success:^(id responseObject) { NSLog(@"Notification sent"); } failure:^(NSError *error) { NSLog(@"error %@", error); }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 | JsonObject message = new JsonObject() .putString("greeting","Hello World!") .putString("from","BaasBox"); BaasUser user = BaasUser.withUserName("Cesare"); user.send(message,new BaasHandler<Void>(){ @Override public void handle(BaasResult<Void> res){ if(res.isFailed()){ Log.e("LOG","Something went wrong",res.error()); } } }); |
1 | TO BE IMPLEMENTED |
Example of a request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | { "message":"test". "profiles":[1], "sound":"sound.wav", "actionLocalizedKey":"Play", "localizedKey":"GAME_PLAY_REQUEST_FORMAT", "localizedArguments":["Jenna","Frank"], "badge":10, "custom": { "data": "text", "title": "Titletext", }, "collapse_key":"update_match_15", "time_to_live":106 } |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // if all OK { "result": "ok", "data": "", "http_code": 200 } //or (in case of errors in settings i.e. push sent to Android & iOS devices but only Android settings are configured) { "result": "ok", "data": "Push notifications were sent but they may be subject to loss of data. HINT: check push settings in console", "http_code": 200, "bb_code": "20001" } |
Collections
A collection is a sort of bucket where you can store documents. Documents are schema-less, which means that there are no constraints on their fields definition or data type. Another very important feature to know about collections is that the records stored have a per-user-record-security-level, meaning that each record can be accessed only by the user who created it. There are APIs to grant or revoke privileges to other users. See Grant permissions on a Document.
Create a new Collection
POST /admin/collection/:collection-name
Creates a new collection.
Parameter | Description |
---|---|
collection-name | The name of the new collection. Mandatory. |
Example of a request to create a collection
1 2 | curl -X POST http://localhost:9000/admin/collection/mycollection \
-H X-BB-SESSION:53331bd8-3dbb-40af-8bcb-252ac908f142
|
1 2 3 4 5 6 7 | BAAClient *client = [BAAClient sharedClient]; [client createCollection:@"mynewcollection" completion:^(id object, NSError *error) { NSLog(@"collection created"); }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /* this api is usable only as administrator using the raw request interface */ BaasBox client = BaasBox.getDefault(); String collectionName = "mycollection"; client.rest(HttpRequest.POST,"admin/collection/"+collectionName,null,true, new BaasHandler<JsonObject>(){ @Override public void handle(BaasResult<JsonObject> res) { if (res.isSuccess()) { Log.d("LOG","Collection created"); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.createCollection("pizzas") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 201 } |
Delete a Collection
DELETE /admin/collection/:collection-name
Deletes an existing collection with the name specified in the URL. The user calling this API must be the admin or belong to the admin role.
Parameter | Description |
---|---|
collection-name | The name of the collection to be deleted. Mandatory. |
Example of a request to delete a collection
1 2 | curl -X DELETE http://localhost:9000/admin/collection/mycollection \
-H X-BB-SESSION:53331bd8-3dbb-40af-8bcb-252ac908f142
|
1 | NOT SUPPORTED |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /* this API is usable only as administrator using the raw request interface */ BaasBox client = BaasBox.getDefault(); String collectionName = "mycollection"; client.rest(HttpRequest.DELETE,"admin/collection/"+collectionName,null,true, new BaasHandler<JsonObject>(){ @Override public void handle(BaasResult<JsonObject> res) { if (res.isSuccess()) { Log.d("LOG","Collection created"); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.deleteCollection("pizzas") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Documents
A document belongs to a Collection. You can create, read, update and delete a document, provided you have access to it.
Here are the APIs.
Create a document
POST /document/:collection-name
Group: baasbox.data.write
Creates a document in the collection specified in the parameter. The collection must have been created in advance. See here. The returned document is decorated with the following fields:
id
: unique Identifier of the document. It is a String and it is unique thorught all the database.@version
: number indication of the version of the record, useful to manage concurrent updates@class
: name of the collection_creation_date
: timestamp_author
: username of the user who created the document.
Note: These fields cannot be overwritten.
Since v0.9.4 you can provide your own ids for documents.
By default only the owner can update and delete the documents he created. All the other users (except admins and backoffice) cannot have any kind of access to those documents, unless they are granted permissions.
Parameter | Description |
---|---|
collection-name | The name of the collection. Mandatory. |
The body payload | A valid JSON as the body of the POST call. Mandatory. |
Example of a request to create a document
1 2 3 4 | curl -X POST http://localhost:9000/document/mycollection \ -d '{"title" : "My new post title", "body" : "Body of my post."}' \ -H Content-type:application/json \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assumes post is an instance of Post, which subclasses BAAObject with properties "title" and "body". Post *post = [[Post alloc] init]; post.title = @"My new post title"; post.body = @"Body of my post."; [post saveObjectWithCompletion:^(Post *p, NSError *error) { if (error == nil) { NSLog(@"saved post is %@", p) } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 | BaasDocument doc = new BaasDocument("mycollection"); doc.putString("title","My new post title") .putString("body","Body of my post."); doc.save(new BaasHandler<BaasDocument>() { @Override public void handle(BaasResult<BaasDocument> res) { if(res.isSuccess()) { Log.d("LOG","Saved: "+res.value()); } else { } } }); |
1 2 3 4 5 6 7 8 9 10 11 | // Assumes a collection named "posts" has been created var post = new Object(); post.title = "My new post title"; post.body = "Body of my post."; BaasBox.save(post, "posts") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "result": "ok", "data": { "@rid": "#25:0", "@version": 2, "@class": "mycollection", "title": "My new post title", "body": "Body of my post.", "id": "090dd688-2e9a-4dee-9afa-aad72a1efa93", "_creation_date": "2014-01-30T21:13:16.016+0100", "_author": "cesare" }, "http_code": 200 } |
Retrieve documents
You can fetch documents in two ways: using their unique IDs, or executing a query to perform a search. Both methods are described below.
Retrieve a document by its ID
GET /document/:collection/:ID
Group: baasbox.data.read
Retrieves the document in the collection specified with the ID provided as parameter. Only the owner of the document (besides users with admin role) can retrieve it.
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
ID | The unique ID of the document. Mandatory. |
Example of a request to retrieve a specific document
1 2 | curl http://localhost:9000/document/mycollection/090dd688-2e9a-4dee-9afa-aad72a1efa93 \
-H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e
|
1 2 3 4 5 6 7 8 9 10 11 | // Assuming Post is a subclass of BAAObject [Post getObjectWithId:@"090dd688-2e9a-4dee-9afa-aad72a1efa93" completion:^(Post *post, NSError *error) { if (error == nil) { NSLog(@"Post is %@", post); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | BaasDocument.fetch("mycollection", "090dd688-2e9a-4dee-9afa-aad72a1efa93", new BaasHandler<BaasDocument>() { @Override public void handler(BaasResult<BaasDocument> res) { if(res.isSuccess()) { BaasDocument doc = res.value(); Log.d("LOG","Document: "+doc); } else { Log.e("LOG","error",res.error()); } }}); |
1 2 3 4 5 6 7 | BaasBox.loadObject("posts", "090dd688-2e9a-4dee-9afa-aad72a1efa93") .done(function(res) { console.log("res ", res['data']); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "result": "ok", "data": { "@rid": "#25:0", "@version": 2, "@class": "mycollection", "title": "My new post title", "body": "Body of my post.", "id": "090dd688-2e9a-4dee-9afa-aad72a1efa93", "_creation_date": "2014-01-30T21:13:16.016+0100", "_author": "cesare" }, "http_code": 200 } |
Retrieve documents by a query
GET /document/:collection
Group: baasbox.data.read
Returns the documents that the user can read in a collection. This API supports Pagination and Query Criteria. This means that you can use, for example, the where criteria to filter the result, the recordsPerPage criteria to limit the number of records to retrieve, and so on. In the where clause you can use the SQL-FILTERING syntax of OrientDB
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
Example of a request to retrieve a list of documents using default pagination
1 2 3 4 5 6 | curl http://localhost:9000/document/mycollection \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e // Version with pagination curl 'http://localhost:9000/document/mycollection?page=0&recordsPerPage=1' \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | // Assumes Post as a subclass of BAAObject [Post getObjectsWithCompletion:^(NSArray *posts, NSError *error) { if (error == nil) { NSLog(@"Posts are %@", posts); } else { // deal with error } }]; // Version with pagination NSDictionary *parameters = @{kPageNumberKey : @0, kPageSizeKey : @20}; [Post getObjectsWithParams:parameters completion:^(NSArray *posts, NSError *error) { if (error == nil) { NSLog(@"Posts are %@", posts); } else { // deal with error } }]; // Apply a filter using the where keyword NSDictionary *parameters = @{@"where" : "color='red'"}; [Post getObjectsWithParams:parameters completion:^(NSArray *posts, NSError *error) { if (error == nil) { NSLog(@"Posts are %@", posts); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | BaasDocument.fetchAll("collection", new BaasHandler<List<BaasDocument>>() { @Override public void handle(BaasResult<List<BaasDocument>> res) { if (res.isSuccess()) { for (BaasDocument doc:res.value()) { Log.d("LOG","Doc: "+doc); } } else { Log.e("LOG","Error",res.error()); } } }); // using pagination and selection Criteria filter = BaasQuery.builder().pagination(0,20) .orderBy("field desc") .where("_author = ?") .whereParams("Cesare") .criteria(); BaasDocument.fetchAll("collection",filter, new BaasHandler<List<BaasDocument>() { @Override public void handle(BaasResult<List<BaasDocument>> res) { if (res.isSuccess()) { for (BaasDocument doc:res.value()) { Log.d("LOG","Doc: "+doc); } } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | BaasBox.loadCollection("posts") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) // Version with pagination BaasBox.loadCollectionWithParams("pizzas", {page: 0, recordsPerPage: BaasBox.pagelength}) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | { "result": "ok", "data": [ { "@rid": "#25:1", "@version": 5, "@class": "mycollection", "title": "My new post title", "body": "Body of my post.", "id": "af1d66fe-c8b6-436f-866b-e4c823ae7666", "_creation_date": "2014-01-30T22:22:36.036+0100", "_author": "cesare" }, { "@rid": "#26:1", "@version": 5, "@class": "mycollection", "title": "My second post title", "body": "Body of my second post.", "id": "af1236fe-c8bs-4r6f-866b-e4cnkutd8636", "_creation_date": "2014-01-30T22:22:38.031+0100", "_author": "cesare" } ], "http_code": 200 } |
Count documents
GET /document/:collection/count
Group: baasbox.data.read
Returns the number of documents that the user can read in a collection. Supports Pagination and Query Criteria.
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
Example of a request to count documents in a collection
1 2 | curl http://localhost:9000/document/mycollection/count \
-H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Assumes Post is a subclass of BAAObject [Post fetchCountForObjectsWithCompletion:^(NSInteger count, NSError *error) { if (error == nil) { NSLog(@"count is %i", count); } else { NSLog(@"error is %@", error); } }]; |
1 2 3 4 5 6 7 8 9 10 | BaasDocument.count("collection",new BaasHandler<Long> () { @Override public void handle(BaasResult<Long> res) { if (res.isSuccess()) { Log.d("LOG","visible document count is: "+res.value()); } else { Log.e("LOG","Error",res.value()); } } }); |
1 2 3 4 5 6 7 | BaasBox.fetchObjectsCount("posts") .done(function(res) { console.log("res ", res['data']['count']); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 | { "result": "ok", "data": { "count": 1 }, "http_code": 200 } |
Modify a document
PUT /document/:collection/:ID
Group: baasbox.data.update
Updates the document with the ID provided in the specified collection. Only the owner of the document (besides backoffice users), can call this API.
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
ID | The unique ID of the document. Mandatory. |
A valid JSON as the body of the PUT. |
Example of a request to modify a document
1 2 3 4 | curl -X PUT http://localhost:9000/document/mycollection/090dd688-2e9a-4dee-9afa-aad72a1efa93 \ -d '{"title" : "My new post title", "body" : "New body of post.", "tags" : "tag1"}' \ -H Content-type:application/json \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assumes post is an instance of Post, which subclasses BAAObject with properties "title", "body" and "tags". post.title = @"My new post title"; post.tags = @"tag1" post.body = @"Body of my post."; [post saveObjectWithCompletion:^(Post *p, NSError *error) { if (error == nil) { NSLog(@"saved post is %@", p) } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | BaasDocument doc = new BaasDocument("post"); doc.putString("title","My new post title") .putString("tags","tag1") .putString("body","Body of my post"); doc.save(SaveMode.IGNORE_VERSION,new BaasHandler<BaasDocument>(){ @Override public void handle(BaasResult<BaasDocument> res) { if(res.isSuccess()){ Log.d("LOG","Document saved "+res.value().getId()); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 8 9 10 11 | // Assumes posts has properties "title", "body" and "tags". post.title = "My new post title"; post.tags = "tag1" post.body = "Body of my post."; BaasBox.save(post, "posts") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | { "result": "ok", "data": { "@rid": "#25:0", "@version": 3, "@class": "mycollection", "title": "My new post title", "body": "New body of post.", "tags": "tag1", "id": "090dd688-2e9a-4dee-9afa-aad72a1efa93", "_creation_date": "2014-01-30T21:13:16.016+0100", "_author": "cesare" }, "http_code": 200 } |
Update a Document’s field
PUT /document/:collection/:id/.:fieldname
Group: baasbox.data.update
Updates a single field of an existing object. The field can be a simple property,
a complex JSON object or even an array using the notation .array[index]
.
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
id | The ID of the document. Mandatory. |
fieldname | The name of the field that you want to update |
data | A JSON object in the body of the PUT. The new value must have a key named data . |
Example of a request to change the value of the ‘title’ field
1 2 3 4 | curl -X PUT http://localhost:9000/document/mycollection/af1d66fe-c8b6-436f-866b-e4c823ae7666/.title \ -d '{"data" : "Updated title"}' \ -H Content-type:application/json \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 2 3 4 5 6 7 8 9 10 11 | // Assumes post is an instance of Post, which subclasses BAAObject with properties "title". post.title = @"My new title"; [post saveObjectWithCompletion:^(Post *p, NSError *error) { if (error == nil) { NSLog(@"saved post is %@", p) } else { // deal with error } }]; |
1 | //Please see the "pass-through" functionality of the Android SDK
|
1 2 3 4 5 6 7 8 | // Assumes post is an instance of Post, which subclasses BAAObject with properties "title". BaasBox.updateField(post.id, "posts", "title", "My new title") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "result": "ok", "data": { "@rid": "#25:1", "@version": 6, "@class": "mycollection", "title": "Updated title", "body": "Body of my post.", "id": "af1d66fe-c8b6-436f-866b-e4c823ae7666", "_creation_date": "2014-01-30T22:22:36.036+0100", "_author": "cesare" }, "http_code": 200 } |
Example of a request to add a new value named 'tags’
1 2 3 4 | curl -X PUT http://localhost:9000/document/mycollection/af1d66fe-c8b6-436f-866b-e4c823ae7666/.tags \ -d '{"data" : ["tag1", "tag2"]}' \ -H Content-type:application/json \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 2 | // Extend the Post class by adding a property named "tags"
// then use the method saveObjectWithCompletion: to save the object.
|
1 | //Please see the "pass-through" functionality of the Android SDK
|
1 | //Please use the $.ajax interface
|
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { "result": "ok", "data": { "@rid": "#25:1", "@version": 7, "@class": "mycollection", "title": "Updated title", "body": "Body of my post.", "id": "af1d66fe-c8b6-436f-866b-e4c823ae7666", "_creation_date": "2014-01-30T22:22:36.036+0100", "_author": "cesare", "tags": [ "tag1", "tag2" ] }, "http_code": 200 } |
Example of a request to add a new value to the 'tags’ array property
1 2 3 4 5 | curl -X PUT http://localhost:9000/document/mycollection/af1d66fe-c8b6-436f-866b-e4c823ae7666/.tags[3] \ --globoff \ -d '{"data" : "newly added tag"}' \ -H Content-type:application/json \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 | //Please see the "pass-through" functionality of the iOS SDK
|
1 | //Please see the "pass-through" functionality of the Android SDK
|
1 | //Please use the $.ajax interface
|
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | { "result": "ok", "data": { "@rid": "#25:1", "@version": 10, "@class": "mycollection", "title": "Updated title", "body": "Body of my post.", "id": "af1d66fe-c8b6-436f-866b-e4c823ae7666", "_creation_date": "2014-01-30T22:22:36.036+0100", "_author": "cesare", "tags": [ "tag1", "tag2", "newly added tag" ] }, "http_code": 200 } |
Example of a request to add a JSON object as a property
1 2 3 4 5 | curl -X PUT http://localhost:9000/document/mycollection/af1d66fe-c8b6-436f-866b-e4c823ae7666/.address \ --globoff \ -d '{"data" : {"street" : "5th Avenue", "zip" : 10021}}' \ -H Content-type:application/json \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 | //Please see the "pass-through" functionality of the iOS SDK
|
1 | //Please see the "pass-through" functionality of the Android SDK
|
1 | //Please use the $.ajax interface
|
Response includes a new property
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | { "result": "ok", "data": { "@rid": "#25:1", "@version": 15, "@class": "mycollection", "title": "Updated title", "body": "Body of my post.", "id": "af1d66fe-c8b6-436f-866b-e4c823ae7666", "_creation_date": "2014-01-30T22:22:36.036+0100", "_author": "cesare", "tags": [ "tag1", "tag2", "newly added tag" ], "address": { "zip": 10021, "street": "5th Avenue" } }, "http_code": 200 } |
Example of a request to change a nested property
1 2 3 4 5 | curl -X PUT http://localhost:9000/document/mycollection/af1d66fe-c8b6-436f-866b-e4c823ae7666/.address/.street \ --globoff \ -d '{"data" : "6th Avenue"}' \ -H Content-type:application/json \ -H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e |
1 | //Please see the "pass-through" functionality of the iOS SDK
|
1 | //Please see the "pass-through" functionality of the Android SDK
|
1 | //Please use the $.ajax interface
|
Response includes a new value for the property
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | { "result": "ok", "data": { "@rid": "#25:1", "@version": 15, "@class": "mycollection", "title": "Updated title", "body": "Body of my post.", "id": "af1d66fe-c8b6-436f-866b-e4c823ae7666", "_creation_date": "2014-01-30T22:22:36.036+0100", "_author": "cesare", "tags": [ "tag1", "tag2", "newly added tag" ], "address": { "zip": 10021, "street": "6th Avenue" } }, "http_code": 200 } |
Delete a document
DELETE /document/:collection/:ID
Group: baasbox.data.write
Deletes the document with the ID specified in the collection provided as parameter. Only the owner of the document (and admin and backoffice users) can delete it, besides users who have been granted the permission to delete.
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
ID | The unique ID of the document. Mandatory. |
Example of a request to delete a document
1 2 | curl -X DELETE http://localhost:9000/document/mycollection/090dd688-2e9a-4dee-9afa-aad72a1efa93 \
-H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e
|
1 2 3 4 5 6 7 8 9 10 | // Assumes post is an instance of Post, which subclasses BAAObject [post deleteObjectWithCompletion:^(BOOL success, NSError *error) { if (success) { NSLog(@"object deleted"); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 | // Assumes doc is an instance of BaasDocument doc.delete(new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res) { if (res.isSuccess()) { Log.d("LOG", "Document deleted"); } else { Log.e("LOG", "error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.delete("090dd688-2e9a-4dee-9afa-aad72a1efa93", "posts") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Grant permissions on a Document
PUT /document/:collection/:id/:action/user/:username
Group: baasbox.data.grants
PUT /document/:collection/:id/:action/role/:rolename
Group: baasbox.data.grants
Grants permission on a document. You can set permissions for a single user or a role name.
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
id | The ID of the document. Mandatory. |
action | The grant you want to assign. One of: read , update , delete , all . Mandatory. |
username | The username of the user to whom you want to assign the grant |
rolename | The name of the role to whom you want to grant the permission. One of: anonymous , registered , administrator , plus those defined by the administrator. Mandatory. |
Example of a request to grant read access to user “a” on document “4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e”
1 2 | curl -X PUT http://localhost:9000/document/mycollection/4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e/read/user/a \
-H X-BB-SESSION:090dd688
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Assumes p is an instance of Post, which is a subclass of BAAObject [p grantAccessToUser:@"cesare" ofType:kAclReadPermission completion:^(id object, NSError *error) { if (error == nil) { NSLog(@"permission granted"); } else { NSLog(@"error in granting permission"); } }]; |
1 2 3 4 5 6 7 8 9 10 11 | // assuming doc is an instance of the document doc.grant(Grant.READ,"a",new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res) { if (res.isSuccess()) { Log.d("LOG","Permission granted"); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.grantAccessToUser("posts", "4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e", BaasBox.READ_PERMISSION, "a") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a request to grant update access to all registered users on a document
1 2 | curl -X PUT http://localhost:9000/document/mycollection/090dd688/update/role/registered \
-H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Assumes p is an instance of Post, which is a subclass of BAAObject [p grantAccessToRole:kAclRegisteredRole ofType:kAclUpdatePermission completion:^(SMPost *post, NSError *error) { if (error == nil) { NSLog(@"permission granted"); } else { NSLog(@"error in granting permission"); } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | // assumes doc is an instance of the document doc.grantAll(Grant.UPDATE,Role.REGISTERED, new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res) { if (res.isSuccess()) { Log.d("LOG","Permission granted"); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.grantAccessToRole("posts", "4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e", BaasBox.UPDATE_PERMISSION, BaasBox.REGISTERED_ROLE) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Revoke permissions on a Document
DELETE /document/:collection/:id/:action/user/:username
Group: baasbox.data.grants
DELETE /document/:collection/:id/:action/role/:rolename
Group: baasbox.data.grants
Revokes permission on a document. You can revoke permissions to a single user or a role name.
Parameter | Description |
---|---|
collection | The name of the collection. Mandatory. |
id | The ID of the document. Mandatory. |
action | The grant you want to assign. One of: read , update , delete , all . Mandatory. |
username | The username of the user to whom you want to assign the grant |
rolename | The name of the role to whom you want to grant the permission. One of: anonymous , registered , administrator , plus those defined by the administrator. Mandatory. |
Example of a request to revoke read access to user “a” on document “4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e”
1 2 | curl -X DELETE http://localhost:9000/document/mycollection/090dd688/read/user/a \
-H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Assumes p is an instance of Post, which is a subclass of BAAObject [p revokeAccessToUser:@"a" ofType:kAclReadPermission completion:^(SMPost *post, NSError *error) { if (error == nil) { NSLog(@"permission granted"); } else { NSLog(@"error in granting permission"); } }]; |
1 2 3 4 5 6 7 8 9 10 11 | // assuming doc is an instance of the document doc.revoke(Grant.READ,"a",new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res) { if (res.isSuccess()) { Log.d("LOG","Permission granted"); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.revokeAccessToUser("posts", "4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e", BaasBox.READ_PERMISSION, "a") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a request to revoke update access to all registered users on a document
1 2 | curl -X PUT http://localhost:9000/document/mycollection/090dd688/update/role/registered \
-H X-BB-SESSION:4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Assumes p is an instance of Post, which is a subclass of BAAObject [p revokeAccessToRole:kAclRegisteredRole ofType:kAclUpdatePermission completion:^(SMPost *post, NSError *error) { if (error == nil) { NSLog(@"permission granted"); } else { NSLog(@"error in granting permission"); } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | // assumes doc is an instance of the document doc.revokeAll(Grant.UPDATE,Role.REGISTERED, new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res) { if (res.isSuccess()) { Log.d("LOG","Permission granted"); } else { Log.e("LOG","Error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.revokeAccessToUser("posts", "4cbfe03c-632b-4d3e-9a2b-0d4a0326d89e", BaasBox.UPDATE_PERMISSION, BaasBox.REGISTERED_ROLE) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Links
Available since 0.8.0
Links allow to connect documents, files and users (since v.0.9.4) to each other. They are similar to the relations in a relational database. Of course there are differences between relations and links. First of all, links have versus, secondly they have a label.
Links are implemented using the graph capabilities of OrientDB that is the database engine embedded in BaasBox.
As an example please see the code aside.
1 2 3 4 5 6 7 8 | customer Document A (out) -------------> (in) Document B Invoices Customers item Document A (out) -------------> (in) Document C Invoices Items |
Basically you can imagine documents and files like nodes in a graph. Each of them is a node that can be connected with others. Nodes are connected by links (or edges). Links have a versus, a label, and a source/destination pair of nodes. For further information on graph databases, nodes, links and how these are managed by OrientDB, please see the official OrientDB WIKI site
You can query links by label and/or use filters to select linked documents (or file). At the moment it is possible to execute query only on links, there are not APIs to traverse them or to query linked documents from a given one.
Create a link
POST /link/:sourceId/:label/:destId
Group: baasbox.data.write
To create a link you must provide the two objects (documents, files, users) you want to connect and the link label (or name). Since links have a direction, the first document will be the source node of the link and the second one will be the destination node.
Parameter | Description |
---|---|
sourceId | The ID of the first document or file to link. |
label | The link name. Can be any valid string |
destId | The ID of the second document or file to link. |
Note: use the users'id, not their username!
1 2 | curl -X POST -H X-BB-SESSION:f24c0ccb-e2bd-4741-8133-86fea6ea1e01 -H x-baasbox-appcode:1234567890 -d '' http://localhost:9000/link/423d56a1-bc83-467d-b27c-897a5f4cd229/customer/a0868a63-0d38-4fc9-93c3-1f9b62eeadf0
|
1 | //Please see the "pass-through" functionality of the iOS SDK
|
1 2 3 4 5 6 7 8 9 | BaasLink.create("customer","source-id","dest-id",RequestOptions.DEFAULT,new BaasHandler<BaasLink>() { @Override public void handle(BaasResult<BaasLink> res) { if (res.isSuccess()){ BaasLink value = res.value(); Log.d("TAG","value is your new link"); } } }); |
1 | //Please use the $.ajax interface
|
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | { "result":"ok", "data":{ "@version":3, "@class":"E", "label":"customer", "id":"994cb9b0-ccba-4ba2-a7dd-68c0440a0783", "_author":"admin", "_creation_date":"2014-05-23T14:37:27.027+0200", "out":{ "@version":2, "@class":"Invoices", "number":345, "id":"423d56a1-bc83-467d-b27c-897a5f4cd229", "_creation_date":"2014-05-23T14:32:40.040+0200", "_author":"admin" }, "in":{ "@version":2, "@class":"Customers", "name":"John Doe", "age":31, "id":"a0868a63-0d38-4fc9-93c3-1f9b62eeadf0", "_creation_date":"2014-05-23T14:32:03.003+0200", "_author":"admin" } }, "http_code":200 } |
The returned link is decorated with the following fields:
id
: unique ID@version
: number indication of the version of the link, just like documents@class
: always equals to “E”_creation_date
: timestamp_author
: username of the user who created the link.- `label’: the provided label
out
: the source object (the first one provided)in
: the destination object (the second one provided)
These fields cannot be overwritten.
The out
and in
fields contain the content of both objects.
REMEMBER: the out
field points to the source, the in
points to the destination, like in the following schema:
Source Doc ----->(out) link (in)----> Dest Doc
Please note that you can have as many links as you want between two documents or files even with the same label.
To create a link, a user has to have at least the read permission on both objects to link.
Retrieve links
GET /link/:id
GET /link
You can retrieve a single link by its ID, or query the entire link-space. Be careful because too many links could be returned. The endpoint supports selection and query criteria, so you can ask the server to filter the response.
Of course you can apply filters to the fields of linked nodes to search for specific links that match the criteria.
GET /link?where=in.name.toLowerCase() like 'john%' and label="customer"
1 2 | curl -X GET -H X-BB-SESSION:f24c0ccb-e2bd-4741-8133-86fea6ea1e01 -H x-baasbox-appcode:1234567890 "http://localhost:9000/link?where=in.name.toLowerCase()%20like%20%27john%25%27%20and%20label%3D%27customer%27"
|
1 | //Please see the "pass-through" functionality of the iOS SDK
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | //single link BaasLink.fetch("id", RequestOptions.DEFAULT,new BaasHandler<BaasLink>() { @Override public void handle(BaasResult<BaasLink> res) { if (res.isSuccess()){ Log.d("TAG",res.value().toString()); } else { Log.d("TAG","Handle error"); } } }); //many liinks BaasQuery.Criteria query =BaasQuery.builder().where("in.name.toLowerCase() like john").criteria(); BaasLink.fetchAll("customer",query,RequestOptions.DEFAULT,new BaasHandler<List<BaasLink>>() { @Override public void handle(BaasResult<List<BaasLink>> res) { if (res.isSuccess()){ List<BaasLink> links = res.value(); Log.d("TAG","Your links are here: "+links.size()); } else { //handle errors } } }); |
1 | //Please use the $.ajax interface
|
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | { "result":"ok", "data":{ "@version":3, "@class":"E", "label":"customer", "id":"994cb9b0-ccba-4ba2-a7dd-68c0440a0783", "_author":"admin", "_creation_date":"2014-05-23T14:37:27.027+0200", "out":{ "@version":2, "@class":"Invoices", "number":345, "id":"423d56a1-bc83-467d-b27c-897a5f4cd229", "_creation_date":"2014-05-23T14:32:40.040+0200", "_author":"admin" }, "in":{ "@version":2, "@class":"Customers", "name":"John Doe", "age":31, "id":"a0868a63-0d38-4fc9-93c3-1f9b62eeadf0", "_creation_date":"2014-05-23T14:32:03.003+0200", "_author":"admin" } }, "http_code":200 } |
Delete links
DELETE /link/:id
Deletes a link.
At the moment links can be deleted by anyone. The RSL (Record Security Level) has not yet been implemented on links.
1 | curl -X DELETE -H X-BB-SESSION:f24c0ccb-e2bd-4741-8133-86fea6ea1e01 -H x-baasbox-appcode:1234567890 -d '' http://localhost:9000/link/994cb9b0-ccba-4ba2-a7dd-68c0440a0783
|
1 | //Please see the "pass-through" functionality of the iOS SDK
|
1 2 3 4 5 6 7 8 | BaasLink.withId("id").delete(RequestOptions.DEFAULT,new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> ok) { if (ok.isSuccess()){ Log.d("TAG","Link has been deleted"); } } }); |
1 | //Please use the $.ajax interface
|
Example of a response
1 2 3 4 5 | { "result":"ok", "data":"", "http_code":200 } |
Files
Users can upload files. Only the user who created them can access such files, besides administrators and users who have the role of “BackOffice”. The maximum size of a file is 2GB, but we do not recommend reaching such size, since BaasBox is a software that provides backend services for mobile Apps. Currently we do not support resume functions for upload and download.
Upload a file
POST /file
Group: baasbox.file.write
API to create and upload a file. By default the uploaded file will be accessible only by the owner, backoffice and admin users. After the uploaded metadata (and exif data in case of images) are extracted and attached to the file. The returned object is decorated with the following fields:
- contetType
- contentLength
- metadata
- textContent
Parameter | Description |
---|---|
file | The file itself. Mandatory. |
attachedData | A valid JSON string to store data associated to a file. Optional. |
acl | A valid JSON string to declare access to the file. Optional. See ACL. |
Example of a request to upload a file
1 2 3 | curl -X POST http://localhost:9000/file \ -F file=@test.jpg \ -H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | NSData *data = ...; // data for file BAAFile *file = [[BAAFile alloc] initWithData:data]; file.contentType = @"image/jpeg"; [file uploadFileWithPermissions:permissions completion:^(BAAFile *uploadedFile, NSError *e) { if (error == nil) { NSLog(@"Uploaded %@", uploadedFile) } else { // Deal with error } }]; // "cesare" and registered users can read, "claudio" can update and all those belonging to "deleters" can delete |
1 2 3 4 5 6 7 8 9 10 11 12 13 | InputStream data = ...; // input stream to upload BaasFile file = new BaasFile(); file.upload(data,new BaasHandler<BaasFile> file) { @Override public void handle(BaasResult<BaasFile> res) { if( res.isSuccess() ) { Log.d("LOG","File uploaded with permissions"); } else { Log.e("LOG","Deal with error",res.error()); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assumes 'uploadForm' is a form with an input tag of type 'file' $("#uploadForm").submit(function(e) { e.preventDefault(); var formObj = $(this); var formData = new FormData(this); BaasBox.uploadFile(formData) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) }); |
Example of a response when a file is created
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | { "result": "ok", "data": { "@version": 2, "_creation_date": "2014-02-03T18:54:17.017+0100", "id": "be81f25d-c954-498e-84a2-6f43a94a9d8f", "_author": "cesare", "fileName": "test.jpg", "contentType": "image/jpeg", "contentLength": 283808, "metadata": { }, "attachedData": { } }, "http_code": 201 } |
Example of a request to create a file with attached data
1 2 3 4 | curl -X POST http://localhost:9000/file \ -F 'attachedData={"test_key":"test_value"}' \ -F file=@test.jpg \ -H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | NSData *data = ...; // data for file BAAFile *file = [[BAAFile alloc] initWithData:data]; file.contentType = @"image/jpeg"; [file.attachedData setObject:@"My title" forKey:@"title"]; [file.attachedData setObject:@[@"tag1", @"tag2"] forKey:@"tags"]; [file uploadFileWithPermissions:permissions completion:^(BAAFile *uploadedFile, NSError *e) { if (error == nil) { NSLog(@"Uploaded %@", uploadedFile) } else { // Deal with error } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | byte[] data = ...; // in memory data to upload JsonObject attachedData = new JsonObject() .putString("someInfo","value"); BaasFile file = new BaasFile(attachedData); file.upload(data,new BaasHandler<BaasFile> () { @Override public void handle(BaasResult<BaasFile> res) { if( res.isSuccess() ) { Log.d("LOG","File uploaded with permissions"); } else { Log.e("LOG","Deal with error",res.error()); } } }); |
1 | TO BE IMPLEMENTED |
Example of a request to create a file with attached data and acl
1 2 3 4 5 | curl -X POST http://localhost:9000/file \ -F '"attachedData"={"test_key":"test_value"}' \ -F '"acl"={"read":{"roles":["registered"]}' \ -F file=@test.jpg \ -H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | NSData *data = ...; // data for file BAAFile *file = [[BAAFile alloc] initWithData:data]; file.contentType = @"image/jpeg"; [file.attachedData setObject:@"My title" forKey:@"title"]; [file.attachedData setObject:@[@"tag1", @"tag2"] forKey:@"tags"]; NSDictionary *permissions = @{kAclReadPermission : @{@"users" : @[@"cesare"], @"roles" : @[kAclRegisteredRole]}, kAclUpdatePermission : @{@"users" : @[@"claudio"]}, kAclDeletePermission : @{@"roles" : @[@"deleters"]} }; [file uploadFileWithPermissions:permissions completion:^(BAAFile *uploadedFile, NSError *e) { if (error == nil) { NSLog(@"Uploaded %@", uploadedFile) } else { // Deal with error } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | InputStream data = ...; // input stream to upload JsonObject attachedData = new JsonObject(); attachedData.putString("key","value") .putLong("num",1); BaasFile file = new BaasFile(attachedData); BaasACL acl = new BaasACL().grantUsers(Grant.READ,"andrea"); file.upload(acl,data,new BaasHandler<BaasFile> file) { @Override public void handle(BaasResult<BaasFile> res) { if( res.isSuccess() ) { Log.d("LOG","File uploaded with permissions"); } else { Log.e("LOG","Deal with error",res.error()); } } } |
1 | TO BE IMPLEMENTED |
Delete a file
DELETE /file/:id
Group: baasbox.file.write
API to delete a file.
Parameter | Description |
---|---|
id | The ID of the file to be deleted. Mandatory. |
Example of a request to delete a file
1 2 | curl -X DELETE http://localhost:9000/file/a57b33ce-7f4d-4ff7-bf8c-f8c0f973b9d8 \
-H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786
|
1 2 3 4 5 6 7 8 9 10 11 12 | BAAFile *picture = ...; // instance or subclass of BAAFile [picture deleteFileWithCompletion:^(BOOL success, NSError *error) { if (success) { NSLog(@"Pic deleted"); } else { // Deal with error } } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | BaasFile file = ...; // a file reference file.delete(new BaasHandler<Void>() { @Override public void handle(BaasResult<Void> res) { if( res.isSuccess() ) { Log.d("LOG","File has been downloaded"); } else { Log.e("LOG","Deal with error",res.error()); } } }); // if you don't have a reference to the file // object but you know it's id BaasFile.delete("fileId",handler); |
1 2 3 4 5 6 7 | BaasBox.deleteFile("0d7c2469-71e0-447b-a524-a8ecd0bf4a77") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response when a file is deleted
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Retrieve a file
GET /file/:id
Group: baasbox.file.read
Parameter | Description |
---|---|
id | The ID of the file to be retrieved. Mandatory. |
download | Set it to true to download a file (useful from browser). Optional. |
resize | Index to retrieve an element from the array of resizing options. Optional. See Console Settings. |
Example of a request to retrieve a file
1 2 | curl http://localhost:9000/file/f18e4343-5100-4398-b32f-2e634220bf99 \
-H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786
|
1 2 3 4 5 6 | BAAFile *picture = ...; // instance or subclass of BAAFile, previously saved on the server [picture loadFileWithCompletion:^(NSData *data, NSError *error) { self.imageView.image = [[UIImage alloc] initWithData:data]; }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // load file in memory BaasFile file = ...; file.stream(new BaasHandler<BaasFile>() { @Override public void handle(BaasResult<BaasFile> res) { if ( res.isSuccess() ) { byte[] data = res.value().getData(); Log.d("LOG","File received"); } else { Log.e("LOG","Error while streaming",res.error()); } } }); //save a file on disk BaasFile file =...; file.download("path-to-save-the-file.to", new BaasHandler<Pair<BaasFile,String>>(){ @Override public void handle(BaasResult<Pair<BaasFile,String>> res)P{ } }); |
1 2 3 4 5 6 7 | BaasBox.fetchFile("0d7c2469-71e0-447b-a524-a8ecd0bf4a77") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 | // Binary file |
Example of a request to suggest the browser to download an app
1 2 | curl http://localhost:9000/file/f18e4343-5100-4398-b32f-2e634220bf99?download=true \ -H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786 |
Example of a request to retrieve a resized version of an app
1 2 | curl http://localhost:9000/file/f18e4343-5100-4398-b32f-2e634220bf99?sizeId=0 \ -H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786 |
Retrieve details of a file
GET /file/details/:id
Group: baasbox.file.read
Retrieves the details of a file, including attachedData
and metadata
.
Parameter | Description |
---|---|
id | The ID of the file whose details are to be retrieved. Mandatory. |
Example of a request to retrieve details of a file
1 2 | curl http://localhost:9000/file/details/f18e4343-5100-4398-b32f-2e634220bf99 \
-H X-BB-SESSION:9952384d-8d78-4399-82d0-7039f832a786
|
1 2 3 4 5 6 7 8 9 10 | [BAAFile loadFileDetails:p.fileId completion:^(BAAFile *file, NSError *error) { if (error == nil) { NSLog(@"file %@", file); } else { // Deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 | BaasFile.fetch(fileId, new BaasHandler<BaasFile> () { @Override public void handle(BaasResult<BaasFile> res) { if (res.isSuccess()) { Log.d("LOG","Your file details"+res); } else { Log.e("LOG","Deal with eror",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.fetchFileDetails("7491d26b-b730-40e7-9587-c0c3f58193c7") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response with file details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | { "result": "ok", "data": { "@version": 6, "id": "f18e4343-5100-4398-b32f-2e634220bf99", "_creation_date": "2014-02-03T23:41:59.059+0100", "_author": "cesare", "fileName": "test.jpg", "contentType": "image/jpeg", "contentLength": 283808, "metadata": { }, "attachedData": { } }, "http_code": 200 } |
Retrieve details of files
GET /file/details
Group: baasbox.file.read
Returns a list of details about the files that the user has access to. Supports Pagination and query criteria.
Example of a request to retrieve details of files
1 2 | curl http://localhost:9000/file/details \
-H X-BB-SESSION:45640ea7-f57f-4ade-b781-4aebc0c364b6
|
1 2 3 4 5 | [BAAFile loadFilesAndDetailsWithCompletion:^(NSArray *files, NSError *error) { NSLog(@"files are %@", files); }]; |
1 2 3 4 5 6 7 8 9 10 | BaasFile.fetchAll(new BaasHandler<List<BaasFile>>() { @Override public void handle(BaasResult<List<BaasFile>> res) { if (res.isSuccess()) { Log.d("LOG","Received result"); } else { Log.e("LOG","Error",res.error()); } } }); |
1 | TO BE IMPLEMENTED |
Example of a response with details of files
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { "result": "ok", "data": [ { "@version": 4, "id": "338ad9e6-1a70-4483-bd46-9764be05def4", "_creation_date": "2014-02-04T00:50:13.013+0100", "_author": "a", "fileName": "41EAE238-0E8F-491D-BA34-C7BFB4EFF595.image/jpeg", "contentType": "image/jpeg", "contentLength": 75642, "metadata": { }, "attachedData": { } }, { } ], "http_code": 200 } |
Grant access to a file
PUT /file/:id/:action/user/:username
Group: baasbox.file.grants
PUT /file/:id/:action/role/:rolename
Group: baasbox.file.grants
API to grant access to a file for a specific user or role.
Parameter | Description |
---|---|
id | The ID of the file. Mandatory. |
action | The grant you want to assign. One of: read , update , delete , all . Mandatory. |
username | The username of the user to whom you want to assign the grant. Mandatory. |
rolename | The name of the role to whom you want to grant the permission. One of: anonymous , registered , administrator , plus those defined by the administrator. Mandatory. |
Example of a request to grant read access to user “a” on a file
1 2 | curl -X PUT http://localhost:9000/file/41368ee4/read/user/a \
-H X-BB-SESSION:b24fa187-797d-49d1-87fb-c99fee3a6588
|
1 2 3 4 5 6 7 8 9 10 11 12 | BAAFile *file = ... ; // instance of file, already saved on the server [file grantAccessToUser:@"a" ofType:kAclReadPermission completion:^(id object, NSError *error) { if (error == nil) { NSLog(@"Permission granted"); } else { // Deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 | BaasFile file=...; // reference to a file already saved on the server file.grant(Grant.READ,"andrea",new BaasHandler<Void>(){ @Override public void handle(BaasResult<Void> res){ if (res.isSuccess()) { Log.d("LOG","andrea can read the file"); } else { Log.e("LOG","deal with error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.grantUserAccessToFile("7491d26b-b730-40e7-9587-c0c3f58193c7", BaasBox.READ_PERMISSION, "a") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a request to grant write access to role “registered” on a file
1 2 | curl -X PUT http://localhost:9000/file/41368ee4/update/role/registered \
-H X-BB-SESSION:b24fa187-797d-49d1-87fb-c99fee3a6588
|
1 2 3 4 5 6 7 8 9 10 11 12 | BAAFile *file = ... ; // instance of file, already saved on the server [file grantAccessToRole:kAclRegisteredRole ofType:kAclUpdatePermission completion:^(id object, NSError *error) { if (error == nil) { // Permission granted } else { // Deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 | BaasFile file=...; // reference to a file already saved on the server file.grantAll(Grant.READ,"registered",new BaasHandler<Void>(){ @Override public void handle(BaasResult<Void> res){ if (res.isSuccess()) { Log.d("LOG","andrea can read the file"); } else { Log.e("LOG","deal with error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.grantRoleAccessToFile("7491d26b-b730-40e7-9587-c0c3f58193c7", BaasBox.UPDATE_PERMISSION, BaasBox.REGISTERED_ROLE) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Revoke access to a file
DELETE /file/:id/:action/user/:username or DELETE /file/:id/:action/role/:rolename
Group: baasbox.file.grants
API to revoke access to a file for a specific user or role.
Parameter | Description |
---|---|
id | The ID of the file. Mandatory. |
action | The grant you want to revoke. One of: read , update , delete , all . Mandatory. |
username | The username of the user to whom you want to revoke the grant. Mandatory. |
rolename | The name of the role to whom you want to revoke the permission. One of: anonymous , registered , administrator , plus those defined by the administrator. Mandatory. |
Example of a request to revoke read access to user “a” on a file
1 2 | curl -X DELETE http://localhost:9000/file/41368ee4/read/user/a \
-H X-BB-SESSION:b24fa187-797d-49d1-87fb-c99fee3a6588
|
1 2 3 4 5 6 7 8 9 10 11 12 | BAAFile *file = ... ; // instance of file, already saved on the server [file revokeAccessToUser:@"a" ofType:kAclReadPermission completion:^(id object, NSError *error) { if (error == nil) { NSLog(@"Permission revoked"); } else { // Deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 | BaasFile file=...; // reference to a file already saved on the server file.revoke(Grant.READ,"andrea",new BaasHandler<Void>(){ @Override public void handle(BaasResult<Void> res){ if (res.isSuccess()) { Log.d("LOG","andrea can read the file"); } else { Log.e("LOG","deal with error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.revokeUserAccessToFile("7491d26b-b730-40e7-9587-c0c3f58193c7", BaasBox.READ_PERMISSION, "a") .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a request to revoke write access to role “registered” on a file
1 2 | curl -X DELETE http://localhost:9000/file/41368ee4/update/role/registered \
-H X-BB-SESSION:b24fa187-797d-49d1-87fb-c99fee3a6588
|
1 2 3 4 5 6 7 8 9 10 11 12 | BAAFile *file = ... ; // instance of file, already saved on the server [file revokeAccessToRole:kAclRegisteredRole ofType:kAclUpdatePermission completion:^(id object, NSError *error) { if (error == nil) { NSLog(@"Permission revoked"); } else { // Deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 | BaasFile file=...; // reference to a file already saved on the server file.revokeAll(Grant.READ,"registered",new BaasHandler<Void>(){ @Override public void handle(BaasResult<Void> res){ if (res.isSuccess()) { Log.d("LOG","andrea can read the file"); } else { Log.e("LOG","deal with error",res.error()); } } }); |
1 2 3 4 5 6 7 | BaasBox.revokeRoleAccessToFile("7491d26b-b730-40e7-9587-c0c3f58193c7", BaasBox.UPDATE_PERMISSION, BaasBox.REGISTERED_ROLE) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Assets
Assets can be either files or JSON objects. They are public and accessible by anyone, even if not authenticated. They are useful to create publicly accessible elements such as images or configuration settings.
Create an asset
POST /admin/asset
Parameter | Description |
---|---|
name | The name of the asset. Must be unique. Mandatory. |
meta | A string representing a valid JSON object. Here you can store any data associated with the asset. Optional. |
file | The file you want to upload. Optional. |
Allows to create an asset.
Example of a request to create a JSON asset
1 2 3 | curl http://localhost:9000/admin/asset \ -d 'name=margherita&meta={"pizzaname": "Margherita", "price": 5}' \ -H X-BB-SESSION:f24c0ccb-e2bd-4741-8133-86fea6ea1e01 |
1 2 | // NOT IMPLEMENTED
// It's only for admins. You can do it in the web console.
|
1 2 | // NOT IMPLEMENTED // It's only for admins. You can do it in the web console. |
1 2 | // NOT IMPLEMENTED // It's only for admins. You can do it in the web console. |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | { "result": "ok", "data": { "@rid": "#19:3", "@version": 18, "@class": "_BB_Asset", "_creation_date": "2014-02-08T10:52:51.051+0100", "id": "98510f1c-a558-4901-9550-71e8add0a6c2", "_author": "admin", "name": "margherita", "meta": { "pizzaname": "Margherita", "price": 5 } }, "http_code": 201 } |
Example of a request to create a file asset with JSON metadata attached
1 2 3 4 5 | curl http://localhost:9000/admin/asset \ --form file=@pizza.jpg \ --form name=margherita \ --form meta='{"name": "Margherita", "price": 5}' \ -H X-BB-SESSION:f24c0ccb-e2bd-4741-8133-86fea6ea1e01 |
1 2 | // NOT IMPLEMENTED
// It's only for admins. You can do it in the web console.
|
1 | // NOT IMPLEMENTED
|
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | { "result": "ok", "data": { "@rid": "#20:0", "@version": 16, "@class": "_BB_FileAsset", "_creation_date": "2014-02-08T11:04:15.015+0100", "id": "00cced22-680d-45d4-944e-28ac9a140572", "_author": "admin", "name": "margherita", "fileName": "pizza.jpg", "contentType": "image/jpeg", "contentLength": 975404, "meta": { "name": "Margherita", "price": 5 } }, "http_code": 201 } |
Retrieve an Asset
GET /asset/:name
Group: baasbox.assets
To retrieve an asset by name.
Parameter | Description |
---|---|
name | The name of the asset. Mandatory. |
Example of a request to retrieve an asset
1 2 | curl http://localhost:9000/asset/margherita \
-H X-BAASBOX-APPCODE:1234567890
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | // If the asset is a JSON BAAClient *client = [BAAClient sharedClient]; [client getPath:@"asset/margherita/data" parameters:nil success:^(id responseObject) { NSLog(@"resp %@", responseObject); } failure:^(NSError *error) { NSLog(@"err %@", error); }]; // If the asset is a file BAAClient *client = [BAAClient sharedClient]; [client getPath:@"asset/margherita" parameters:nil success:^(id responseObject) { NSLog(@"resp %@", responseObject); } failure:^(NSError *error) { NSLog(@"err %@", error); }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // if it's a JSON BaasAsset.fetchData("name",new BaasHandler<JsonObject>() { @Override public void handler(BaasResult<JsonObject> res) { if(res.isSuccess()){ // do something with the object } else { Log.e("ERROR","Error while retrieving asset",res.error()); } } }); // if it's binary BaasAsset.streamAsset("name",new BaasHandler<byte[]>() { @Override public void handler(BaasResult<byte[]> res){ if(res.isSuccess()) { // do something with content } else { Log.e("ERROR","Error while retrieving asset",res.error()); } } }); ```1 ```javascript TO BE IMPLEMENTED |
Example of a response
1 | The file itself or the JSON |
Delete an asset
DELETE /admin/asset/:name
Allows to delete an asset.
Parameter | Description |
---|---|
name | The name of the asset. Mandatory. |
Example of a request to delete an asset
1 2 | curl -X DELETE http://localhost:9000/admin/asset/margherita \
-H X-BB-SESSION:f24c0ccb-e2bd-4741-8133-86fea6ea1e01
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | BAAClient *client = [BAAClient sharedClient]; [client deletePath:@"admin/asset/margherita" parameters:nil success:^(id responseObject) { NSLog(@"resp %@", responseObject); } failure:^(NSError *error) { NSLog(@"err %@", error); }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
Fetch assets
GET /admin/asset
Allows to retrieve all the assets. Supports Pagination and query criteria.
Example of a request to fetch assets
1 2 | curl http://localhost:9000/admin/asset \
-H X-BB-SESSION:f24c0ccb-e2bd-4741-8133-86fea6ea1e01
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | BAAClient *client = [BAAClient sharedClient]; [client getPath:@"admin/asset" parameters:nil success:^(id responseObject) { NSLog(@"resp %@", responseObject); } failure:^(NSError *error) { NSLog(@"err %@", error); }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | { "result": "ok", "data": [ { "@rid": "#19:7", "@version": 18, "@class": "_BB_Asset", "_creation_date": "2014-02-08T11:54:09.009+0100", "id": "63db6a92-5e74-4bbe-aeff-982eaba10d3e", "_author": "admin", "name": "margherita", "meta": { "pizzaname": "Margherita", "price": 5 } }, { "@rid": "#19:8", "@version": 27, "@class": "_BB_Asset", "_creation_date": "2014-02-08T11:56:20.020+0100", "id": "591c583c-dd78-4ba1-acab-331b9559b8fd", "_author": "admin", "name": "marinara", "meta": { "pizzaname": "Marinara", "price": 4 } } ], "http_code": 200 } |
API Settings
Settings are app-related configuration options. They are intended to set up many app-specific parameters, like the app name, the push notification certificate supplied by Apple, and so on. Settings are split in different sections or topics.
More information can be found here
Fetch current settings
GET /admin/configuration/dump.json
Returns a JSON representing the current configuration.
1 2 3 | curl http://localhost:9000/admin/configuration/dump.json \ -H X-BB-SESSION:4efcd048-8865-4047-94c9-8ac58e511b4b \ -H X-BAASBOX-APPCODE:1234567890 |
1 2 3 4 5 6 7 8 9 10 | BAAClient *client = [BAAClient sharedClient]; [client loadSettingsWithCompletion:^(NSDictionary *settings, NSError *error) { if (error == nil) { NSLog(@"settings are %@", settings); } else { NSLog(@"error %@", error); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | { "result": "ok", "data": [ { "section": "PasswordRecovery", "description": "Configurations for password recovery related properties", "sub sections": { "email": [ { "email.template.text": "Hi ...", "type": "String" } ], "network": [ ] } }, { "section": "Application", "description": "Configurations for general App(lication) related properties", "sub sections": { } }, { "section": "Push", "description": "Configurations for push related properties", "sub sections": { } }, { "section": "Images", "description": "Configurations for Images related stuffs", "sub sections": { } }, { "section": "Social", "description": "Configurations for Social Login related stuffs", "sub sections": { } } ], "http_code": 200 } |
Fetch a section of the Settings
GET /admin/configuration/:section
Returns a JSON representing a section of the configuration.
Parameter | Description |
---|---|
section | The name of a section. One of: PasswordRecovery , Application , Push , Images . Mandatory. |
Example of a request to retrieve the `Application` section
1 2 3 | curl http://localhost:9000/admin/configuration/Application \ -H X-BB-SESSION:4efcd048-8865-4047-94c9-8ac58e511b4b \ -H X-BAASBOX-APPCODE:1234567890 |
1 2 3 4 5 6 7 8 9 10 11 | BAAClient *client = [BAAClient sharedClient]; [client loadSettingsSection:@"Application" completion:^(NSDictionary *settings, NSError *e) { if (error == nil) { NSLog(@"apps settings %@", settings); } else { NSLog(@"error %@", e); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | { "result": "ok", "data": [ { "key": "application.name", "value": "BaasBox", "description": "The App name", "type": "String" }, { "key": "session_tokens.timeout", "value": "0", "description": "The expiration time of the session tokens (in minutes). WARNING: the admin console refreshes the session token every 5 minutes, if you set a value lower than 5, you may experience disconnection from the console. To disable expiration set it to 0.", "type": "Integer" }, { "key": "network.http.ssl", "value": "false", "description": "Set to TRUE if the BaasBox server is reached via SSL through a reverse proxy.", "type": "Boolean" }, { "key": "network.http.url", "value": "localhost", "description": "The public url of the BaasBox server. I.e. the url used by the App to contact BaasBox, without the protocol prefix (i.e. http://) and PORT", "type": "String" }, { "key": "network.http.port", "value": "9000", "description": "The public TCP port used by the App to contact BaasBox. Please note: when behind a reverse proxy, this could be different from the port used by BaasBox.", "type": "Integer" } ], "http_code": 200 } |
Update a value in settings
PUT /admin/configuration/:section/:key/:value
Updates a specific value in the settings.
Parameter | Description |
---|---|
section | The name of a section. One of: PasswordRecovery , Application , Push , Images . Mandatory. |
key | The name of the key to update. Mandatory. |
value | The new value for the key. Mandatory. |
Example of a request to update the key `application.name`
1 2 3 | curl -X PUT http://localhost:9000/admin/configuration/Application/application.name/NewName \ -H X-BB-SESSION:4efcd048-8865-4047-94c9-8ac58e511b4b \ -H X-BAASBOX-APPCODE:1234567890 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | BAAClient *client = [BAAClient sharedClient]; [client setValue:@"MyAppName" forKey:@"application.name" inSection:@"Application" completion:^(NSDictionary *settings, NSError *e) { if (e == nil) { NSLog(@"settings are %@", settings); } else { NSLog(@"error %@", e); } }]; |
1 | TO BE IMPLEMENTED |
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "", "http_code": 200 } |
REST API Access
REST API access control lets you manage which endpoints are accessible from the outside world. Each endpoint belongs to a named group, identified by a key.
Disabled groups render their endpoints inaccessible to clients, unless the user is authenticated as an administrator: the client will receive a forbidden status code instead of the usual response.
By default all groups are enabled.
List groups
GET /admin/endpoints
The predefined groups are all prefixed with baasbox., and cover all the endpoints except for the administrative ones that cannot be turned off.
Function Group | Description |
---|---|
baasbox.assets | rules the read access to assets and related content |
baasbox.account | rules the login/logout and account modification endpoints |
baasbox.account.create | rules the ability to create a new user account (signup) |
baasbox.social | rules the ability to use social login APIs |
baasbox.account.lost_password | rules the ability to use the recover password functionality |
baasbox.users | rules the access to the baasbox users |
baasbox.friendship | rules the read access to friendship endpoints |
baasbox.friendship.create | rules the write access to friendship endpoints |
baasbox.notifications.send | rules the ability to send notifications (push messages) |
baasbox.notifications.receive | rules the ability to subscribe to notifications (push messages) |
baasbox.data.write | rules the ability to create new documents in collections |
baasbox.data.read | rules the read access to collections and documents |
baasbox.data.update | rules the ability to update existing documents |
baasbox.data.grants | rules the ability to modify grants on documents |
baasbox.file.read | rules the ability to read/list files |
baasbox.file.write | rules the ability to create new files |
baasbox.file.grants | rules the ability to modify grants on files |
Example of a request to list endpoint groups
1 2 3 | curl -X GET http://localhost:9000/admin/endpoints \ -H X-BB-SESSION:4efcd048-8865-4047-94c9-8ac58e511b4b \ -H X-BAASBOX-APPCODE:1234567890 |
1 |
|
1 |
|
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | { "result": "ok", "data": { "baasbox.assets": true, "baasbox.account": true, "baasbox.account.create": true, "baasbox.social": true, "baasbox.account.lost_password": true, "baasbox.users": true, "baasbox.friendship": true, "baasbox.friendship.create": true, "baasbox.notifications.send": true, "baasbox.notifications.receive": true, "baasbox.data.write": true, "baasbox.data.read": true, "baasbox.data.update": true, "baasbox.data.grants": true, "baasbox.file.read": true, "baasbox.file.write": true, "baasbox.file.grants": true }, "http_code": 200 } |
Read specific group
GET /admin/endpoints/:group-name
Returns details about a group. Useful to know if a specific group of APIs is enabled or not.
Parameter | Description |
---|---|
group-name | The name of the group of endpoints |
Example of a request to get a specific endpoint group
1 2 3 | curl -X GET http://localhost:9000/admin/endpoints/baasbox.assets \ -H X-BB-SESSION:4efcd048-8865-4047-94c9-8ac58e511b4b \ -H X-BAASBOX-APPCODE:1234567890 |
1 |
|
1 |
|
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 6 7 8 | { "result": "ok", "data": { "tag": "baasbox.assets", "enabled": true }, "http_code": 200 } |
Enable an endpoint group
PUT /admin/endpoints/:group-name/enabled
This API enables a group of endpoints
Parameter | Description |
---|---|
group-name | The name of the group of endpoints |
Example of a request to enable an endpoint group
1 2 3 | curl -X PUT http://localhost:9000/admin/endpoints/baasbox.assets/enabled \ -H X-BB-SESSION:4efcd048-8865-4047-94c9-8ac58e511b4b \ -H X-BAASBOX-APPCODE:1234567890 |
1 |
|
1 |
|
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "success", "http_code": 200 } |
Disable an endpoint group
DELETE /admin/endpoints/:group-name/enabled
This API disables a group of endpoints. Calls to endpoints belonging to this group will return an error 403.
Parameter | Description |
---|---|
group-name | The name of the group of endpoints |
Example of a request to disable an endpoint group
1 2 3 | curl -X DELETE http://localhost:9000/admin/endpoints/baasbox.assets/enabled \ -H X-BB-SESSION:4efcd048-8865-4047-94c9-8ac58e511b4b \ -H X-BAASBOX-APPCODE:1234567890 |
1 |
|
1 |
|
1 | TO BE IMPLEMENTED |
Example of a response
1 2 3 4 5 | { "result": "ok", "data": "success", "http_code": 200 } |
Plugin Engine
Since v.0.9.0 you can write your own scripts (plugins) to run inside BaasBox.
To create a plugin please see the Console
The entire plugin reference is located on GitHub
1 2 | NOTHING HERE. See other tabs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // Example with GET // Assumes this plugin is installed on the server: https://gist.github.com/funkyboy/ecc754dbe0f89e4a4c56 BAAClient *c = [BAAClient sharedClient]; [c getPath:@"/plugin/geo.bb" parameters:@{@"ip" : @"8.8.8.8"} success:^(id responseObject) { NSLog(@"res %@", responseObject); } failure:^(NSError *error) { NSLog(@"error %@ ", error); }]; // Example with POST // Assumes this plugin is installed https://gist.github.com/funkyboy/ad3b25dfdbd53e27324f BAAClient *c = [BAAClient sharedClient]; [c postPath:@"/plugin/addcar.bb" parameters:@{@"name" : @"ferrari"} success:^(id responseObject) { NSLog(@"res %@", responseObject); } failure:^(NSError *error) { NSLog(@"error %@ ", error); }]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // plugins are invoked through pass-through // eg: BaasBox box =BaasBox.getDefault(); box.rest(HttpRequest.POST, "plugin/mywonderful.plugin", new JsonObject().put("bodyVal", 2), true, new BaasHandler<JsonObject>() { @Override public void handle(BaasResult<JsonObject> res) { Log.d("TAG","Ok: "res.isSuccess()); } }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Example with GET // Assumes this plugin is installed on the server: https://gist.github.com/funkyboy/ecc754dbe0f89e4a4c56 var url = BaasBox.endPoint + '/plugin/geo.bb'; $.get(url, {"ip" : "8.8.8.8"}) .done(function (res) { console.log("res is ", res.data); }) .fail(function (error) { console.log("error = ", error); }) // Example with POST // Assumes this plugin is installed https://gist.github.com/funkyboy/ad3b25dfdbd53e27324f var url = BaasBox.endPoint + '/plugin/addcar.bb'; $.post(url, {"name" : "ferrari"}) .done(function (res) { console.log("res is ", res.data); }) .fail(function (error) { console.log("error = ", error); }) |
Use Cases
Geospatial Queries
Since BaasBox is based on OrientDB, you can use any function that this NoSQL database has. One of these functions is distance() that returns the distance in Km between two points on the globe. How can you use this feature?
Let’s say you have a collection of POIs, and each record has a latitude and longitude stored as degrees in two fields, you can get all the POIs within a certain radius:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | "poi" collection: { "lat": 41.890210, "long": 12.492231, "name": "Colosseum" }, { "lat": 41.902916, "long": 12.453389, "name": "Vatican City" }, { "lat": 40.690050, "long": -74.045068, "name": "Liberty Island" } |
Once you have retrieved the device position through its sensors, you can perform a query like “Hey, BaasBox, gimme the POIs around me in a radius of 5 Km”. For example, if you are visiting Rome:
GET /document/poi?where=distance(lat,long,41.872389,12.480180) < 5
What if you also want know the distance?
GET /document/poi?fields=name,distance(lat,long,41.872389,12.480180) as dist&where=distance(lat,long,41.872389,12.480180) < 5
BaasBox returns the name and distance of the POIs that satisfy the where criteria.
Remember that by default the query is executed only on records that the user can actually read.
This is amazing if you want to manage private and public POIs, because the filter is automatically applied.
1 | curl -X GET -H "x-baasbox-appcode:1234567890" -H "Authorization:Basic YWRtaW46YWRtaW4=" http://localhost:9000/document/poi?where=distance\(lat,long,41.872389,12.480180\)+%3C+5 |
1 2 3 4 5 6 7 8 9 10 | // Assumes Poi as a subclass of BAAObject NSDictionary *parameters = @{@"where" : "distance(lat,long,41.872389,12.480180) < 5"}; [Poi getObjectsWithParams:parameters completion:^(NSArray *pois, NSError *error) { if (error == nil) { NSLog(@"POIs are %@", pois); } else { // deal with error } }]; |
1 2 3 4 5 6 7 8 9 10 11 12 | private static final BaasQuery PREPARED_QUERY = BaasQuery.builder() .collection("poi") .where("distance(lat,long,41.872389,12.480180) < 5") .build(); PREPARED_QUERY.query(new BaasHandler<List<JsonObject>>(){ @Override public void handle(BaasResult<List<JsonObjec>> res){ // handle result or failure } }); |
1 2 3 4 5 6 7 | BaasBox.loadCollectionWithParams("poi", {where:"distance(lat,long,41.872389,12.480180) < 5"}) .done(function(res) { console.log("res ", res); }) .fail(function(error) { console.log("error ", error); }) |
Password Recovery
BaasBox has a function for Password Recovery that allows the users of your App to reset their password in case they forgot it.
In order to make use of this function it is important that upon signup the App sends to BaasBox the email address of the user in the email field of the visibleByTheUser object, as you will see in the following example.
PUT /me
Example of a request
1 2 3 | { "visibleByTheUser":{"email":"email_of_the_user@email.com"} } |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 | { "result": "ok", "data": { "visibleByTheUser": { "email": "email_of_the_user@email.com" }, ... ... ... }, "http_code": 200 } |
By the way it is possible to create a user with email address
POST /user
Example of a request
1 2 3 4 5 6 7 | { "username":"user", "password":"user", "visibleByTheUser":{ "email":"email_of_the_user@email.com" } } |
Example of a response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "result": "ok", "data": { ... ... ... "visibleByTheUser": { "email": "email_of_the_user@email.com" ... ... ... }, "http_code": 201 } |
Finally, the App has to call the reset password API whenever requested. This is
GET user/:username/password/reset
If you get the following response:
1 2 3 4 5 6 7 8 9 10 11 | { "result": "error", "message": "Cannot send mail to reset the password: Could not reach the mail server. Please contact the server administrator", "resource": "/user/test/password/reset", "method": "GET", "request_header": { ... ... ... }, } |
this means that you got something wrong in the set up.
The fields you need to set up in order to have the Password Recovery service function are the following:
- email.from: the sender of the Password Recovery email (your email address);
- network.smtp.authentication: to be set to TRUE if the server requires authentication;
- network.smtp.host: IP ADDRESS or fully qualified name of the SMTP server;
- network.smtp.password: the password of the sender’s email account;
- network.smtp.port: the port used by the SMTP server: SSL or TLS;
- network.smtp.ssl:TRUE/FALSE according to the use of SSL or TLS;
- network.smtp.tls:TRUE/FALSE a seconda della volontà di usare SSL o TLS;
- network.smtp.user: MUST be the same account in the email.from field (INCLUDING THE DOMAIN i.e. @email.com);
N.B. IT IS NOT POSSIBLE TO HAVE BOTH THE NETWORK.SMTP.SSL AND NETWORK.SMTP.TLS FIELDS SET TO TRUE, ONE OF THEM HAS TO BE SET TO FALSE.
Password Recovery with Gmail account
In order for the Gmail account to be “enabled” to send the Password Recovery email, you need to enable the access to less secure Apps. The page on which you can make this choice is the following, activating this setting for the Gmail account set in the email.from parameter.
References: Less secure Apps.
The fields you need to set up in order to have the Password Recovery service work on Gmail accounts are the following:
- email.from: the sender of the Password Recovery email (your Gmail address);
- network.smtp.authentication: to be set to TRUE if the server requires authentication, and Gmail does;
- network.smtp.host: IP ADDRESS or fully qualified name of the SMTP server, in this case smtp.gmail.com;
- network.smtp.password: the password of the sender’s Gmail account;
- network.smtp.port: the port used by the SMTP server: SSL (465) or TLS (587);
- network.smtp.ssl:TRUE/FALSE according to the use of SSL or TLS ;
- network.smtp.tls:TRUE/FALSE according to the use of SSL or TLS;
- network.smtp.user: MUST be the same account of the email.from field (INCLUDING THE DOMAIN @GMAIL.COM);
N.B. IT IS NOT POSSIBLE TO HAVE BOTH THE NETWORK.SMTP.SSL AND NETWORK.SMTP.TLS FIELDS SET TO TRUE, ONE OF THEM HAS TO BE SET TO FALSE.
How to query with the Creation Date
In order to perform correctly the query with the creation date you must write the following statement
1 | _creation_date > date('2014-09-09T17:59:47.772+0200') |
just beware of encoding it correctly to be passed as a query parameter.