baasbox documentation - read the docs · – push notifications for ios and android devices •db...

72
baasbox Documentation Release 0.7.3 baasbox March 18, 2014

Upload: others

Post on 25-Mar-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox DocumentationRelease 0.7.3

baasbox

March 18, 2014

Page 2: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,
Page 3: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

Contents

1 Introduction 3

2 Installation 5

3 General Overview 73.1 Available Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.2 Applied Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

4 Custom Error Code 9

5 Console 115.1 The login screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.2 The Dashboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.3 Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145.4 Database Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155.5 Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165.6 Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.7 Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195.8 Assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

6 RestAPI 236.1 REST API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

7 SDK 577.1 SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577.2 Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677.3 Hacking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

i

Page 4: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

ii

Page 5: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Contents:

Contents 1

Page 6: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

2 Contents

Page 7: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

CHAPTER 1

Introduction

BaasBox is a complete solution to implement the back end of your applications.

You can access all sections using the sidebar on the left. The documentation explains:

• the BaasBox features (server side)

– how to install BaasBox

– how to use admin console and has a detailed section about the REST API that you can use

– REST API

• the SDK features

– iOS SDK

For a complete list of changes and new features, see changelog

The Getting Started section will allow you to rapidly have a first result of what BaasBox can give you. Enjoy!

3

Page 8: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

4 Chapter 1. Introduction

Page 9: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

CHAPTER 2

Installation

System Requirements Java VM 6 or above. BaasBox is compiled with Java 1.6

1. Download the latest version from the download page, keep in mind that until the 1.0 version will be released,BaasBox is not production-ready and therefore subject to change. For Windows Platforms on the same page youwill find the start.tar.gz file.

2. Unzip the file baasbox-x.x.zip wherever you want.

3. Only for Windows Platforms: unzip the start.tar.gz file and put the extracted start.bat in the same directory

4. Type:

• start.bat (on Windows)

• ./start (on *nix) You might need to grant execution permissions via

chmod +x ./start

BaasBox will start and listen on port 9000. Visit http://localhost:9000/ with your preferred browser. Ifeverything 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 isready to go and to serve your apps! To stop the server just halt (Ctrl-C) the shell script.

5

Page 10: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

6 Chapter 2. Installation

Page 11: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

CHAPTER 3

General Overview

BaasBox is a server that makes available a set of functions for the backend of mobile applications. All you need is aJava Virtual Machine 1.6 or above. BaasBox already has everything you need for it to work: an application serverand a DB server. BaasBox was born to be simple to use and manage. To migrate a BaasBox instance from a serverto another, you just have to zip the database folder and copy it in the server target folder. Moreover, it is ready to usewithout changing the configuration parameters. You just have to launch the command ./start (or start.bat onWindows) and BaasBox will run. Shoud you need it, you can apply customize configuration parameters.

3.1 Available Functions

Available functions are:

• Administration console:

– A convenient web based administration console is provided, through which the administrator can manageseveral aspects 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 asso-ciate arbitrary JSON data

• Users management:

– Signup, Login, Logout, profiles management (private, public features and so on), forgotten password re-covery, link and log-in through Facebook and Google+

– Roles management: administrators, registered users, back-office users, creation of new roles.

• Push notifications:

– Push notifications for iOS and Android devices

• DB management:

– Backup/restore and reset of the integrated database

7

Page 12: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

3.2 Applied Technology

BaasBox is written mostly in Java, with some code in Scala. It uses the Play! Framework and it incorporates the coreof the OrientDB database. This will allow BaasBox to natively manage the relations between JSON objects and to linkobjects and queries without using specific abstractions or having to simulate them on the applicative level. OrientDBwas recently surveyed and entered Gartner’s Magic Quadrant.

8 Chapter 3. General Overview

Page 13: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

CHAPTER 4

Custom Error Code

Custom Error Code

These are the custom error codes made by BaasBox

• 40001: You are attempting to update a database object with older data. Versions are not the same

• 40101: Invalid or not provided authentication info. HINT: Has your session expired?

• 50301: Push settings are not properly configured. HINT: go to 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)

9

Page 14: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

10 Chapter 4. Custom Error Code

Page 15: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

CHAPTER 5

Console

BaasBox has a web console that allows managing its behavior and performing administrative tasks. The consoleis a responsive one-page web application that performs REST calls to the BaasBox admin APIs. This guide willillustrate the console for the version 0.7.3 We suppose that BaasBox is deployed on localhost with its default pa-rameters. If you deployed BaasBox in the correct way, you can open your browser and open the welcome screen:

11

Page 16: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

5.1 The 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 the administrator credentials and the Application Code. Bydefault these values are:

• Username: admin

• Password: admin

• App Code: 1234567890

You can change these values at any time by following the instructions shown in the Hacking. By clicking on thequestion marks, the fields will be filled with the default values.

12 Chapter 5. Console

Page 17: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

5.2 The 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 splittedinto several sections:

1. BaasBox version number

2. Quick link to the BaasBox site

3. Main menu to access all the main sections of BaasBox

4. A trace of where you are located

5. Number of users and rapid access to the relative section

6. Number of documents (objects) stored in the embedded database and rapid access to the relative section

7. Quick link to the download of BaasBox site where you can find the latest version

8. Number of collections, documents and total size in one window.

9. Here you can see all the latest news about BaasBox. These are feeds from the BaasBox site

5.2. The Dashboard 13

Page 18: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

10. 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 version with its path and data size

11. Access to a dialog window to change 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.

12. Feedback tab: from there you can send us a feedback about your experience with BaasBox

13. DB Management: you can create backup of your DB and import/export

14. Roles: you can view and create roles for users

15. Files: here you will find the files you have uploaded and you will be able to manage them and work on them

NOTE: you can hide all tables/sections that have the up-arrow button on the right.

5.3 Settings

By selecting the Settings option in the left menu you can access the settings section. You can choose settings forapplications, password recovery, images and push notifications. Each record has the Edit button that allows you tomodify its action.

NOTE: the starred fields are mandatory.

14 Chapter 5. Console

Page 19: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

5.4 Database Management

The item DB Management allows you to perform some operations on the database.

1. Restore a previously created backup file

2. Create a new backup

3. View the list of generated backups

4. Reinitialize the database. 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 itin 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.

5.4. Database Management 15

Page 20: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

5.5 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:

16 Chapter 5. Console

Page 21: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

NOTE

1. The starred fields are mandatory

2. After you filled in at least the mandatory fields, you have to save the changes

5.6 Collections

By selecting the Collections option on the menu you can access the collection administrationpage. Collections are a sort of buckets where you can store objects, also known as “documents”.

5.6. Collections 17

Page 22: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

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.

18 Chapter 5. Console

Page 23: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

5.7 Documents

Documents are objects stored in the embedded NoSQL database ad grouped in “Collections”

In this section you have the list of all your documents, but you have to select an existing collection at first. Infact you can see all the documents relative to a specific collection. Of course you also have the search tool.

5.7. Documents 19

Page 24: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Each document has a unique ID, generated by the server once it is stored. Data documents are stored and retrievedJSON format.

Documents are accessible only by the user that created them. APIs exist to grant and revoke permissions to the singleusers or roles.

5.8 Assets

Assets are special objects. They are public by default, but only administrators can create or delete them. They canstore arbitrary data (in JSON format), or entire files. Each Asset can store a file and its associated data. Assets do nothave IDs generated by the server, but you can, indeed you MUST, assign a unique name to them. You can subsequentlyuse these names to reference the assets.

In this section you have the 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 NewAsset button and you will see the following window:

20 Chapter 5. Console

Page 25: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

NOTE: you have to fill in at least the Name field and save the changes to create a new asset.

5.8. Assets 21

Page 26: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

22 Chapter 5. Console

Page 27: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

CHAPTER 6

RestAPI

Contents:

6.1 REST API

6.1.1 General Remarks

These are the general notes about the REST API protocol used by BaasBox and its JSON format.

Request Headers

If not specified otherwise, all requests need some custom HTTP headers.

These are BaasBox Authentications headers, since the 0.5.7 version supports two authentication methods: HTTPBasic Authentication, or via a Session Token.

Basic Authentication

It needs to provide the user’s credentials via the basic access authentication method. Username and password must becombined into a string “username:password” and then encoded using BASE64. The header must be in the form:Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== . If the authentication fails, the serverreplies with BAD REQUEST http error (code 400) X-BAASBOX-APPCODE: This is the application code, by defaultthis is: 1234567890

Session Token

To use this authentication method, the client has to call the /users/login API. The Server will provide a tokento use in the subsequent calls. All tokens will be invalidated if the server is stopped. To pass the session token to theserver, use the following header:

X-BB-SESSION: 0000-1111-2222-3333

The JSON response

Every response generated by BaasBox as a result of a REST call is a JSON object with the following structure:

23

Page 28: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

{

"result": "ok|ko",

"http_code": (200|201|204),

"data": {

...the data themselves...

}

}

In case of error, the data returned are more detailed and are useful to understand why the request was rejected. In thiscase, the JSON format is:

{

"result": "error",

"bb_code": xxx,

"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..."

}

For bb_code see below.

Custom Error Codes

These are custom error codes specific to BaasBox

• 40001: You are attempting to update a database object with older data. Version is not the same

• 40101: Invalid or not provided authentication info. HINT: Has your session expired?

• 50301: Push settings are not properly configured. HINT: go to 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)

Query Criteria

Some APIs allow to specify query criteria. Accepted parameters are:

• where: set a filter criteria in a SQL-like fashion (i.e.: “color=’yellow’ oraddress.city=’rome’”). It is possible to use the positional mode, for example: “color=? or

24 Chapter 6. RestAPI

Page 29: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

address.city=?”. In this case you must supply the parameters’ values using the params querystringparameter. NOTE:the value of the parameter must be URL encoded.

• params: an array of value for the where clause. For example:/API\_URL/WHERECLAUSE/&params=yellow&params=cyan

• orderBy: set an order by clause in a SQL-like fashion (i.e.: orderBy name desc). NOTE: the direction ofordering (asc or desc) is mandatory if pagination is used (see below)

• page: a 0 based index indicating the page requested

• recordPerPage: the number of records per page

• fields: allow 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 byOrientDB into the “select” statements. An exaustive list of available functions is availableat https://github.com/orientechnologies/orientdb/wiki/SQL-Where#wiki-field-operators, meanwhile the ex-planation of how to specify projections is at https://github.com/orientechnologies/orientdb/wiki/SQL-Query#projections

• groupBy: allow to indicate a “group by” criteria to group the result-set by one or more fields just like in standardSQL statements. This criteria is used in conjunction with the aggregate functions expressed into the “fields”

Example of valid calls: /document/mycoolestcollection/count?where=color%3D’yellow’/document/mycoolestcollection/count?where=color%3D%3F&params%3dyellow/document/documents/count?where=color%3D%3F%20or%20color%3D%3F&params=yellow&params=cyan

6.1.2 Users

Users

Create a user

POST /user

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 registereduser role and they willpost new content, will retrieve their own content, will change their password.

Body payload A JSON object like this:

{

"username":"{username}",

"password":"{password}",

"visibleByTheUser": {...},

"visibleByFriend": {...},

"visibleByRegisteredUsers": {..},

"visibleByAnonymousUsers": {...}

}

• username and password fields are mandatory.

6.1. REST API 25

Page 30: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• visibleByTheUser is an object whose fields are private and visible only by the user

• visibleByFriend is an object whose fields are visible by the user and his/her friends (for future friendshipmanagement)

• visibleByRegisteredUsers is an object whose fields are visible by the user, his/her friends, any registered user

• visibleByAnonymousUsers is an object whose fields are public and visible by everyone, even anonymous users

Returns:

• Code 400: ‘username’ or ‘password’ fields are missing

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 201: user created

User Login (Sign in)

POST /login

Headers: Content-Type: application/x-www-form-urlencoded

Description: Checks username/password and grants the user the right

to execute other calls. This API returns a session token that must be provided into subsequent calls.

Body payload

username={username}&password={password}&appcode={appcode}&login_data={“os”:”{ios|android}”, “devi-ceId”:”{. . . . . . ..}”}

• username: mandatory. The username of the user

• password: mandatory. The user’s password

• appcode: mandatory. The APP CODE (by default it is 1234567890)

• login_data: optional. It may contain relevant information about user device, used to send him push notification.The login_data field, if present, must be a valid JSON object containing two fields: os to specify the deviceoperating system, and deviceId which is the device id provided by Apple or Google when the App requires tohandle their push notification (see tutorials to know how to request it). os could be both ios for ios (Apple)devices, or android for Android (Google) devices.

Example of valid login_data content is:

{

"os":"android",

"deviceId":"xxxxxxxxxxxxxx"

}

Note that in this way a user could login from different devices at the same time.

Returns:

• Code 500: the server cannot fulfill the request, an internal server error occurred

• Code 401: user unauthorized to perform the operation

• Code 400: ‘username’, ‘password’ or ‘appcode’ field is missing

26 Chapter 6. RestAPI

Page 31: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• Code 200: OK. The server replies with a JSON object containing the X-BB-SESSION field which is the sessiontoken to use in subsequent requests as a request header

{

"result": "ok",

"http_code": 200,

"data": {

"X-BB-SESSION": "9b3c7234-e0eb-4861-8a25-6874d232efd0"

}

}

Note that if not used the token will expire in 15 minutes. In that case a new login must be performed. The tokenexpiration does not delete the device ID info so the user may continue to receive push notifications.

User Logout

POST /logout

Headers: X-BB-SESSION: The Session Token

• X-BB-SESSION must contain the session token provided by the login API

Description: This API allows a user to logout from the App

Returns:

• Code 500: the server cannot fulfill the request, an internal server error occurred

• Code 400: The session token is malformed or expired, the server cannot retrieve the App Code associated

• Code 200: OK. the user has successfully logged out.

POST /logout/:deviceId

Headers: X-BB-SESSION: The Session Token

• X-BB-SESSION must contain the session token provided by the login API

Parameters

• deviceId: the deviceId used in the login API

Description: This API allows a user to logout from the App on a specific device. Push notification will not be sent tothe user through the specified device.

Returns:

• Code 500: the server cannot fulfill the request, an internal server error occurred

• Code 400: The session token is malformed or expired, the server cannot retrieve the App Code associated

• Code 200: OK. the user has successfully logged out. The associated device has been removed.

6.1. REST API 27

Page 32: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Password Reset

GET /user/:username/password/reset

Headers: X-BAASBOX-APPCODE: The App Code

Parameters

• username: the username of the user who wants to reset the password

Description: Allows to reset a user password. This API is useful when a user forgot their password and needsto reset it. In order to work, this function needs an email field to be present with a valid email addressthat in thevisibleByTheUser field of the user profile. This is the workflow of this function: A user needs to reset their forgottenpassword. The App must call the /user/:username/password/reset API where :username is the placeholder to substitutewith the username. The server checks if the email address is present within the visibleByTheUser fields in the userprofile. The server sends an email to that address with a generated link to follow to reset the password. The user opensthe email and opens the given link in a web browser. A form is shown with two html password fields. The user fillsin the two fields and submits the form. A confirmation message is shown by the server Many settings can be setup bythe administrator via the Settings menu in the admin console, or via the Settings API Some of them are: The SMTPServer configuration. The email message to be sent The HTML Form to show in order to reset the password. Theconfirmation and the error web page

Returns:

• Code 500: the server cannot fulfill the request, an internal server error occurred

• Code 400: the X-BAASBOX-APPCODE header is not valid or it is empty or the email address is not configuredfor the given user

• Code 200: OK. The reset email was sent

Test if a username already exists

Not yet implemented GET /user/:username/exists

Headers: See the General Remarks

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 401: Credentials supplied in the ‘authorization’ header are invalid or missing

Logged users

Retrieve current user profile

GET /me

Headers: See the General Remarks for authentication hints.

Description: Retrieves the information about the user. Specifically the following JSON is returned:

{

"visibleByTheUser": {...},

"visibleByFriend": {...},

28 Chapter 6. RestAPI

Page 33: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

"visibleByRegisteredUsers": {...},

"visibleByAnonymousUsers": {...}

}

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 401: Credentials supplied in the ‘authorization’ header are invalid or missing

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK: retrieves he JSON object representing the current user

Update current user

PUT /me

Headers: See the General Remarks

Body payload A JSON object like this:

{

"visibleByTheUser": {...},

"visibleByFriend": {...},

"visibleByRegisteredUsers": {..},

"visibleByAnonymousUsers": {...}

}

• visibleByTheUser is an object whose fields are private and visible only by the user

• visibleByFriend is an object whose fields are visible by the user and their friends (for future friendship man-agement)

• visibleByRegisteredUsers is an object whose fields are visible by the user, their friends, any registered user

• visibleByAnonymousUsers is an object whose fields are public and visible by everyone, even anonymous users

Description: Update an user profile information.

The four JSON objects are optional. Using this API you can send just one of them or all four.

PAY ATTENTION: The previously stored content for each of the JSON objects will be overwritten with what was sentthrough this API.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 401: Credentials supplied in the ‘authorization’ header are invalid or missing

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK: retrieves the JSON object representing the current user

6.1. REST API 29

Page 34: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Change password

PUT /me/password

Headers: See the General Remarks

Body payload A JSON object like this:

{

"old": "the old password",

"new": "the new password"

}

both old and new fields are mandatory.

Description: Changes the password of a user.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 401: Credentials supplied in the ‘authorization’ header are invalid or missing

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 400: the old password is invalid

• Code 200: OK

Follow and Unfollow Users

Create a friendship relation

POST /follow/:username

Headers: See authorization header in the General Remarks

Description: This API allows a user to create a friendship relationship with another user whose username is the onespecified in the :username URL component. Once the friendship relation has been created, the follower will be able tosee the documents created by the followed user as well as its visibleByFriends data in its user profile

Returns:

• Code 201: (CREATED) response code if the operation is successful

• Code 404: (NOT FOUND) response if the username provided does not exists

• Code 400: (BAD REQUEST) if the relationship between users already exists

Delete a friendship relation

DELETE /follow/:username

Headers: See authorization header in the General Remarks

Description: This API allows a user to delete a friendship relationship with another user whose username is the onespecified in the :username URL component.Once the friendship relation has been deleted the follower will not be ableto see the documents created by the followed user as well as its visibleByFriends data in its user profile.

30 Chapter 6. RestAPI

Page 35: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Returns:

• Code 200: (OK) response code if the operation is successful

• Code 404: (NOT FOUND) response if the username provided does not exists or if the relationship does notexists

Get all following

GET /following

Headers: See authorization header in the General Remarks

Description: This API returns a list of users that are followed by the current one (the one that made the call). Themethod returns in its data property an array filled with the user profiles representing its “friends”. Each profile willcontain the visibleByFriends data which would be otherwise protected.

Returns:

• Code 200: (OK) response code if the operation is successfull

Returns an empty collection instead of error 404 if elements not exist.

Get following by username

GET /following/:username

Headers: See authorization header in the General Remarks

Parameters

• username: the username of the user who wants to get the following user

Description: This API returns a list of users that are followed by the user passed in parameter. In its data prop-erty the method returns an array filled with the user profiles representing its friends. Each profile will contain thevisibleByFriends data, which would be otherwise protected.

Returns:

• Code 200: (OK) response code if the operation is successful

Returns an empty collection instead of error 404 if elements do not exist.

Get all followers

GET /followers

Headers: See authorization header in the General Remarks

Description: This API returns the list of followers. The method returns in its data property an array filled with theuser profiles representing its “friends”. Each profile will contain the visibleByFriends data which would beotherwise protected. This API supports filter criteria, sorting, pagination

Returns:

• Code 200: (OK) response code if the operation is successful

• Code 404: (NOT FOUND) response if the user does not have any friend relationships

6.1. REST API 31

Page 36: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Get followers by username

GET /followers/:username

Headers: See authorization header in the General Remarks

Parameters

• username: the username of the user who wants to get the followers user.

Description: This API returns the list of followers by the username passed in parameter. In its data property the methodreturns an array filled with the user profiles representing its friends. Each profile will contain the visibleByFriendsdata which would be otherwise protected. This API supports filter criteria, sorting, pagination

Returns:

• Code 200: (OK) response code if the operation is successful

• Code 404: (NOT FOUND) response if the user does not have any friend relationships

Click here for the Social Login section

Social Login

Available since version 0.7.2

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 networkitself. 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 valuesmust be stored into the BaasBox database in order to use BaasBox social feature: you can access the social login tabfrom the settings menu in the admin console.

Then click on the specific social network you are working on and fill in the form with the keys and press Save. Youcan disable the social feature for a specific social network by pressing the disable xxx button

32 Chapter 6. RestAPI

Page 37: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Once you have connected to a social network you can use any client library to obtain the OAuth tokens for usersaccount, and store them with the social API provided by BaasBox.

You can find an application example and tutorial ‘here http://www.baasbox.com/social-login/‘_:

API documentation

Retrieve all social network connections for 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 atthe moment of login/linking. An example of the returned data is:

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 asspecified 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 thesocial network itself.

Returns:

• 200 code with a JSON object which data property contains all the linked social networks 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

6.1. REST API 33

Page 38: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Url parameters

:socialNetwork could be facebook or google

Parameters:

• oauth_token: the oauth_token obtained after user authentication and authorization with a client library (seeexample ‘here http://www.baasbox.com/social-login/‘_:)

• oauth_secret: the oauth_secret obtained after user authentication and authorization with a client library (seeexample ‘here http://www.baasbox.com/social-login/‘_:)

This method allows to login into the BaasBox app using the tokens obtained by a social network client library. If theuser has already logged in with same tokens the server will simply return the X-BB-SESSION token that will be usedfor further requests.

If the user does not exist it will be created and an X-BB-SESSION token will be returned. Upon user creation somedata will be extracted from the social network profile and they will be stored inside the user object. A username will beuniquely generated (to prevent username collision). Therefore after a succesfull login, if necessary, the client app mayask for a username and update the user object accordingly.(See the example ‘here http://www.baasbox.com/social-login/‘_:)

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)

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 http://www.baasbox.com/social-login/‘_:)

oauth_secret: the oauth_secret obtained after user authentication and authorization with a client library (see example‘here http://www.baasbox.com/social-login/‘_:)

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 invokedwith the X-BB-SESSION header.

Returns: - 200 code with an empty response if the linking was succesful, - 401 code if any of the mandatory headerswas missing, - 500 code if something on the server went wrong (i.e. another user with the same tokens already exists)

34 Chapter 6. RestAPI

Page 39: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

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 socialnetwork login and the specified social network is the only one linked to the user, an error will be raised (as the userwill not be available to connect anymore).

Returns: - 200 code with an empty response if the unlink procedure was successful, - 400 code if the user was notlinked to specified social network, - 401 code (Unauthorized) if any of the mandatory header was missing, - 500 codeif something on the server went wrong (i.e. the user was generated and it had only a connection with a social network)

6.1.3 Documents

Create a document

POST /document/:collection

Headers: See authorization header in the General Remarks

Description: Create a new document into the specified collection. The collection must exist and must have beenpreviously created by the admin.

Body payload Any valid JSON string.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: the collection specified does not exist

• Code 200: OK and unique ID will be returned.

NOTE on Record Security Level

The owner can update and delete documents. Their friends (feature not fully implemented) can only see the documents.All other users but the admins cannot have any kind of access to the documents.

Modify a document

PUT /document/:collection/ID

Headers: See authorization header in the General Remarks

Description: Updates the document content. WARNING: the content is replaced, neither added nor merged. Only theowner of the document and the admin, or backoffice users, can modify it.

Body payload Any valid JSON string.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

6.1. REST API 35

Page 40: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• Code 403: FORBIDDEN, the user does not have the necessary privilege to update the document

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: the collection specified does not exist

• Code 200: OK and the internal JSON document representation.

Retrieve a document

GET /document/:collection/ID

Headers: See authorization header in the General Remarks

Description: Retrieves the specified document Only the owner of the document and the admin or backoffice users canretrieve it.

Anonymous users can retrieve documents

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 403: FORBIDDEN, the user does not have the necessary privilege to update the document

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: the collection specified does not exist

• Code 200: OK and the internal JSON document representation.

Delete a document

DELETE /document/:collection/ID

Headers: See authorization header in the General Remarks

Description: Delete a document in the specified collection. Only the owner of the document and the admin orbackoffice users can delete it.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 204: Document deleted

• Code 404: Document not found, or collection not found or document doesn’t belong to the collection

Count the number of documents in a collection

GET /document/:collection/count

Headers: See authorization header in the General Remarks

Description: Returns the number of documents that the USER COULD READ in a collection. Pay attention becausethere could be documents that the user cannot read, and therefore are not included

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 404: the collection does not exist

36 Chapter 6. RestAPI

Page 41: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK, and a JSON list of documents

Retrieves a list of Documents

GET /document/:collection

Headers: See authorization header in the General Remarks

Description: Returns the documents that the USER CAN READ in a collection. Pay attention because there could bedocuments that the user cannot read, and therefore will not be retrieved

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 404: the collection does not exist

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK, and a JSON list of documents

Grant/revoke user/role

PUT /document/:collection/:id/:action/user/:username

or

PUT /document/:collection/:id/:action/role/:rolename

Headers: See authorization header in the General Remarks

Description: Returns the documents that the USER CAN READ in a collection. where:

• collection is the name of the collection

• id is the unique id of the document belonging to the :collection

• action is the kind of grant you want to give:”read”, “update”, “delete”, “all”

• username is the user to give the grant

• rolename is the name of a role. In this case every user belonging to that role will have the specified grant.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 404: the collection does not exist

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK

To revoke a permission just use DELETE instead of PUT

Update objects fields

Available since version 0.7.2

Starting from version 0.7.2 it is possible to update single fields of an object in a collection without sending the wholeobject JSON representation to the server .

6.1. REST API 37

Page 42: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

A new endpoint was added to the BaasBox Document API

PUT /document/:collection/:id/(.:fieldName)+

Headers: See authorization header in the General Remarks

Description: Modify a single field specified by the fieldname parameter: the fieldName must start with a . (dot). Itcould be a simple property or a complex JSON object or even an array using the notation .array[index] where the indexis a valid integer.

Body payload: A JSON object with a “data” field (see examples below)

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 403: FORBIDDEN, the user does not have the necessary privilege to update the document

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: the specified collection does not exist

• Code 200: OK and the internal JSON document representation

Some examples of the new API

We will use the simple object below to explain the new feature modifying its fields:

{"title":"a simple post","content":"the content of this awesome post"}

Saving the object to a posts collection will return the object with the following ID a1b45ea7-7005-4f24-ae5e-76a6840ab856

Let’s say we want to modify the title

Making a PUT request to the following URL /document/posts/a1b45ea7-7005-4f24-ae5e-76a6840ab856/.title andwith the following request body

{"data":"this is the new title"}

Will return the following JSON

{"result": "ok","data": {

"@ID": "#24:0","@version": 3,"@class": "posts","title": "this is the new title","content": "the content of this awesome post","id": "a1b45ea7-7005-4f24-ae5e-76a6840ab856"

},"http_code": 200}

As you can see we are using a dot before the field name in the URL of the request.

A post without tags is not a real post so let’s add it as an array of strings:

Making a PUT request to the following URL /document/posts/a1b45ea7-7005-4f24-ae5e-76a6840ab856/.tags andwith the following request body

38 Chapter 6. RestAPI

Page 43: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

{"data":["awesomeness","tag1","tag2"]}

Will return the following JSON:

{"result": "ok","data": {

"@ID": "#24:0","@version": 4,"@class": "posts","title": "this is the new title","content": "the content of this awesome post","id": "a1b45ea7-7005-4f24-ae5e-76a6840ab856","tags": [

"awesomeness","tag1","tag2"

]},"http_code": 200}

As you can see a tags field was added to the object.

Now let’s say that we want to add an element to this tags array:

Making a PUT request to the following URL /document/posts/a1b45ea7-7005-4f24-ae5e-76a6840ab856/.tags[3] withthe following request body

{"data":"new tag"}

Will return:

{"result": "ok","data": {

"@ID": "#24:0","@version": 5,"@class": "posts","title": "this is the new title","content": "the content of this awesome post","id": "a1b45ea7-7005-4f24-ae5e-76a6840ab856","tags": [

"awesomeness","tag1","tag2","new tag"

]},"http_code": 200

}

And what if we want to modify a tag at a specific index?

Making a PUT request to the following URL /document/posts/a1b45ea7-7005-4f24-ae5e-76a6840ab856/.tags[3] withthe following request body

{"data":"new tag modified"}

Will return

6.1. REST API 39

Page 44: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

{"result": "ok","data": {

"@ID": "#24:0","@version": 6,"@class": "posts","title": "this is the new title","content": "the content of this awesome post","id": "a1b45ea7-7005-4f24-ae5e-76a6840ab856","tags": [

"awesomeness","tag1","tag2","new tag modified"

]},"http_code": 200

}

And what about nested objects:

Making a PUT request to the following URL /document/posts/a1b45ea7-7005-4f24-ae5e-76a6840ab856/.author withthe following request body

{"data":{"name":"admin","roles":["admin","superawesome","superuser"]}}

Will return

{"result": "ok","data": {

"@ID": "#24:0","@version": 9,"@class": "posts","title": "this is the new title","content": "the content of this awesome post","id": "a1b45ea7-7005-4f24-ae5e-76a6840ab856","tags": [

"awesomeness","tag1","tag2","new tag modified"

],"author": {

"roles": ["admin","superawesome","superuser"

],"name": "admin"

}},"http_code": 200}

The author object was added and we can also modify its inner properties

Making a PUT request to the following URL /document/posts/a1b45ea7-7005-4f24-ae5e-76a6840ab856/.author/.roles[3] with the following request body

40 Chapter 6. RestAPI

Page 45: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

{“data”:”optimus prime”}

Will return:

{"result": "ok","data": {

"@ID": "#24:0","@version": 10,"@class": "posts","title": "this is the new title","content": "the content of this awesome post","id": "a1b45ea7-7005-4f24-ae5e-76a6840ab856","tags": [

"awesomeness","tag1","tag2","new tag modified"

],"author": {

"roles": ["admin","superawesome","superuser","optimus prime"

],"name": "admin"

}},"http_code": 200}

6.1.4 Files

Available since version 0.7.3

BaasBox has been able to store and manage files since its 0.7.3 version. Every registered user can store files ofany kind and associate an arbitrary JSON object to them, as Assets already can. Unlike them, however, only theuser who created them, administrators and users who have the role of “BackOffice” can access such files, as wellas the documents. Moreover, it is possible to enter queries through selection and ordering criteria on the JSON dataassociated to the files.

The maximum size of a file is 2GB, but we do not recommend reaching such size, since BaasBox is a software thatprovides backend services for mobile Apps. Currently we do not support resume functions for upload and download.

Create a file

POST /file

Headers: See General Remarks and:

• content-type: multipart/form-data

Description: This API stores a new file into the BaasBox embedded DB.

Body payload The body can contain the following fields:.

• file: MANDATORY. The file itself

6.1. REST API 41

Page 46: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• attachedData: optional. A string representing a valid JSON string. Here you can store any data associated to thefile.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 400: the “file” field is not present in the received request

• Code 401: unauthorized user

• Code 201: file created

• Code 200: OK and unique ID will be returned

If BaasBox stores a file, it will return a JSON string with all the data representing the file itself, including the uniqueidentifier (ID) to retrieve it later.

Delete a file

DELETE /file/:id

Headers:

• See General Remarks

• User must have the right to delete the file

Description: This API deletes a given file

Parameters

• id: the unique identifier of the file

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 401: user unauthorized

• Code 404: file not found

• Code 200: OK. The file has been deleted

Stream a file

GET /file/:id

Headers:

• See General Remarks

• User must have the right to read the file

Description: Stream the content of the file to the client

Parameters:

• id: the unique identifier of the file

QueryString:

42 Chapter 6. RestAPI

Page 47: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• download: when true the “Content-Disposition” header with the attachment; filename=”<filename>” valueis sent. This allows the browsers to download the file instead of trying to manage it themselves (as it happenswith images for example)

• resize: same as assets (whose explanation you can look at) it tells the server that the image you want to retrievehas to be resized. Allowed values are those defined in the image settings.

• sizeId: same as assets. Instead of specifying a value for resizing, it refers to the list of allowed formats. Thisvalue is a zero-based array index relating to the list of those values allowed in the image settings.

Image settings The value list for allowed formats is not comma-separated, as wrongly stated so far, but it is space-separated. A new format was added: <=nnpx where nn is the number of pixels. With this format we want the size ofthe returned image to be no more than nn pixels both in height and in width. Basically, should one of the two exceedthe value of nn, it automatically gets resized to nn and the other parameter scales, keeping the same aspect ratio.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 401: user unauthorized

• Code 404: file not found

• Code 200: OK. The file content is returned

Retrieve a file details

GET /file/details/:id

Headers:

• See General Remarks

• User must have the right to read the file

Description: Returns relevant data about a stored file:

• the original file name

• its content type

• its content length

• its attached data

• the user that stored the ID

• the storage data

Parameters

• id: the unique identifier of the file

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 401: user unauthorized

• Code 404: file not found

• Code 204: Document deleted

6.1. REST API 43

Page 48: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Retrieve only the attached data for a given file:

GET /file/attachedData/:id

Headers:

• See General Remarks

• User must have the right to read the file

Description: Returns the attached data related to a given file. IE: returns the JSON object sent when the file has beencreated.

Parameters:

• id: the unique identifier of the file

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 401: user unauthorized

• Code 200: OK. The data are returned

Retrieves details of all the stored files

GET /file/details

Headers:

• See General Remarks

• User must have the right to read the files

Description: Returns relevant data about all the stored files. Please note that only the files that can actually be readfrom the user are returned.

For each file the following data are returned:

• the original file name

• its content type

• its content length

• its attached data

• the user that stored id

• the storage date

NOTE: this API supports QueryStrings selection and sort criteria. Please refer to the Query Criteria section in theGeneral Remarks page.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 401: user unauthorized

• Code 404: file not found

44 Chapter 6. RestAPI

Page 49: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• Code 200: OK. The data are returned

Grant/revoke user/role

PUT /file/:id/:action/user/:username or PUT /file/:id/:action/role/:rolename

Headers: See authorization header in the General Remarks

Description: Grant a user (o an entire role) specific permission on a file.

Parameters:

• :id is the unique id of the file

• action is the kind of grant you want to give “read”, “update”,

“delete”, “all”

• :username is the user to give the grant

• :rolename is the name of a role. in this case every user belonging to that role will have the specified grant

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 404: the id does not exist

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK

To revoke a permission just use DELETE instead of PUT

6.1.5 Assets

IMPORTANT: To create the Assets you must use the related Assets

Retrieve

GET /asset/:name

If the asset is a file, this API retrieves the file. In the response header the server will indicate the file content-type.

Example:

http://localhost:9000/asset/testimg

If the caller is a browser and the asset is an image, the browser will show the image itself.

WARNING: the name to use in the GET request is the one that was set up in the name field when the asset was created,not its file name sent to the server.

WARNING 2: If the asset is an object, an error 404 is sent.

GET /asset/:name/data

Retrieves the related data of the asset, including the meta field supplied at the time of creation and, if the asset is a file,the file name, the file dimension, the content type.

GET /asset/:name/download If the asset is a file, this API streams its content adding the header Content-Disposition: attachment; filename= This header forces the browser to download the file, even if its content type isknown. Please note that the user agent could ignore this header.

6.1. REST API 45

Page 50: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

6.1.6 Push Notifications

Push notifications are messages that a user can send to another user, using an APP that has BaasBox as back-end.Supported platforms are Android and iOS. There are some limitations about sent messages. These limitations areimposed by the operating system vendor. To enable the Push Notification system, please read the tutorial and see theSetting API

Enable push notifications for a device:

PUT /push/device/:os/:deviceId

Headers: See authorization header in the General Remarks

Parameters

• os: the device operating system. This can be either ios or android. Other platforms are not supported yet

• deviceId: the unique identifier of the device. This identifier is released by Google and Apple. Please read thetutorial to know how to obtain it.

Description: This API allows to associate an user to a device, this means that from now on the user will be able toreceive push notifications by the App. Both parameters are mandatory. Returns:

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 200: OK. The device is successfully registered

Send a push notification:

POST /push/message/:username

Headers: See authorization header in the General Remarks

Parameters

• username: mandatory. The recipient of the message

Description: This API allows to send a push notification to another user. Body payload A JSON object like this:

{“message”:”hi guy”

}

The message field must contain the message to deliver. Please read the Push Notification tutorial to know how tohandle push notifications and how to setup the BaasBox server. Note In order to work, the Push Notification systemwithin BaasBox needs to be configured supplying some mandatory information like an API Key released by Google(for Android devices), or Push Certificates released by Apple (for iOS devices). A push notification can be deliveredonly if the recipient has sent its device and operating system info through the login API or the register_device API. Ifa user performs a login using more than a device, a push notification will be sent for each of them. Returns:

• Code 503: push notifications not properly configured

• Code 500: the server cannot fulfill the request, an internal server error occurred

• Code 401: authentication info not valid or not provided

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code or Content-Type not set to appli-cation/json

• Code 200: push notification was sent

46 Chapter 6. RestAPI

Page 51: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

6.1.7 Settings

Settings or “App Configuration” are App related configuration options. These settings are not intended to act atserver configuration level, such as, for example, listening port, or log location, but they are intended to set up manyAPP specific parameters, like the App name, the Push Certificate supplied by Apple, and so on. Settings are split indifferent sections or topics.

Available sections are:

• PasswordRecovery: this section contains many settings that affect the password recovery workflow

• Application: Application specific parameters, such as the App Name

• Push: Push notifications related settings

• Images: specific settings for images (Assets file) processing

PLEASE NOTE that only users belonging to administrator roles can call these APIs

Retrieve current settings

GET /admin/configuration/dump.json

Headers: Please See General Remarks

Parameters: None

Description: Returns a JSON representing the current configuration. The JSON has the following format:

{

"result": "ok",

"http_code": 200,

"data": [

{

"section": "...the section name",

"description": "... a brief description of the section....",

"sub sections": {

"..a subsection ...": [

{

"...a key of a setting...": "...the value...",

"description": "...the key description...",

"type": "...the data type of the value..."

},

....

Returns:

6.1. REST API 47

Page 52: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• Code 500: the server cannot fulfill the request, an internal server error occurred

• Code 400: the X-BAASBOX-APPCODE header is not valid or is empty

• Code 401: The user is not authorized

• Code 200: OK

Retrieve only one section

GET /admin/configuration/:section

Headers: Please See General Remarks

Parameters

• section: one valid setting section

Description: Retrieves the settings of a specific section in a key-value form. The returned JSON is:

{

"result": "ok",

"http_code": 200,

"data": [

{

"key": "...the key of the setting...",

"value": "...its value...",

"description": "...the setting description...",

"type": "...the value data type..."

},

....

Modify a value of a specific setting

PUT /admin/configuration/:section/:key/:value

Headers: Please see the General Remarks

Parameters

• section: one valid setting section

• key: the key of the setting to modify

• value: the new value

Description: Modifies the value of a specific setting. The new value must be of the specific key data type.

48 Chapter 6. RestAPI

Page 53: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

6.1.8 Admin

DB Management

Export database

POST /admin/db/export

Headers: See the General Remarks

Description: Generate a full dump of the db in an asynchronous task.

P.S. The async nature of the method DOES NOT ensure the creation of the file.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: file not created

• Code 202: ACCEPTED and returns the filename of the file that will be generated

Retrieve all backup files

GET /admin/db/export

Headers: See the General Remarks

Description: Returns the list as a JSON array of all the export files stored into the db export folder

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK and returns a JSON representation containing the list of files stored in the db backup folder

Retrieve a backup file

GET /admin/db/export/:filename

Headers: See the General Remarks

Description: Returns a file in the backup folder

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: file not present

• Code 200: OK and returns the stream of the file

6.1. REST API 49

Page 54: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Drop a database

DELETE /admin/db/:timeout

Headers: See the General Remarks

Description: Drops the database with a timeout (if specified) and creates a new clean one (returns to initial stage)

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK

Delete a backup file

DELETE /admin/db/export/:filename

Headers: See the General Remarks

Description: Deletes an export file from the db backup folder, if it exists

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: file not found

• Code 200: OK: the file was correctly deleted

Import database

POST /admin/db/import

Headers: See the General Remarks

Description: Uploads a JSON export file and applies it to the db.

WARNING: all data on the db will be wiped out before importing

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 200: OK

Collections

A collection is a sort of bucket where you can store documents. Documents, also known as records, are schema-less,which means that there are no constraints on their fields definition or data type.

Soon BaasBox will provide methods to set up a sort of constraint at schema level.

The records stored in a collection have a per-user-record-security-level. I.e. each record can be accessed only by theuser who created them. Of course there are APIs to grant or revoke privileges to other users.

50 Chapter 6. RestAPI

Page 55: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Create a new collection

POST /admin/collection/{collection name}

Headers: See general_remarks

Description: Creates a new collection with the name specified in URL. User must belong to the Admin Role. Thename of a collection MUST start with an alphabetic character, CAN contain any alphanumeric character (Latin lettersand Arabic numerals). Underscore and dash are also allowed. The name of a collection is treated as case-insensitive.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 400: collection name is invalid

• Code 403: the user is not an Admin

• Code 201: collection created

Delete a collection

DELETE /admin/collection/{collection name}

Headers: See general_remarks

Description: Deletes an existing new collection with the name specified in the URL. The user calling this API mustbelong to the Admin Role.

Warning: When you delete a collection all the objects stored in it are deleted as well.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 400: collection name is invalid

• Code 403: the user is not an Admin

• Code 201: collection deleted

Users

Admin APIs to manage users

Retrieve all the registered users: GET /admin/user

Headers: See the General Remarks

QueryString: See the General Remarks

Description: Returns a JSON list of all current registered users

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 400: an attempt of potential sql-injection attack has been detected. Check the query string parameters

6.1. REST API 51

Page 56: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• Code 200: OK: Retrieve the list of all users but the default admin user

Admin APIs to manage follow/unfollow

Create a follow relationship: POST /admin/Fw/:follower/to/:tofollow

Headers: See the General Remarks

Description: Create a follow relationship between user follower and user to follow

Parameters:

• follower: user follower

• tofollow: user to follow

Returns:

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: both or either users do not exist

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 400: user :follow is already a friend of :tofollow

• Code 400: cannot create followship relationship with internal users

• Code 200: OK

Delete a follow relationship: DELETE /admin/Fw/:follower/to/:tofollow

Headers: See the General Remarks

Description: Delete a follow relationship between user follower and user to follow

Parameters:

• follower: user follower

• tofollow: user to follow

Returns:

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 404: user :follower is not a friend of :tofollow

• Code 404: both or either users do not exist

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 200: OK

Assets

Assets are a special kind of records. First of all, they can be both files or JSON documents. Furthermore they areaccessible by anyone, even without authentication. They are useful to create publicly accessible elements such as, forexample, images.

52 Chapter 6. RestAPI

Page 57: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Create an Asset

POST /admin/asset

Headers See the General Remarks and:

1. to create an object (JSON document) asset

• content-type: x-www-form-urlencoded

2. to create a file asset

• content-type: multipart/form-data

Description: This API creates a new asset. The user must belong to the admin role.

Body payload The body can contain the following fields:

• name: MANDATORY. The name of the asset.

• meta: optional. A string representing a valid JSON string. Here you can store any data associated with theasset. PAY ATTENTION: since assets are public, everyone could retrieve these data.

• file: optional. If the asset is of the file kind, this is the file you have to load.

NOTE: the server automatically detects if you are posting a file or not by the content-type header. So pay attentionand set up the correct value.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 403: the user is not an Admin

• Code 201: Asset created

Examples Object Asset:

curl -d "name=objectAsset&meta={\"name\": \"Pizza\", \"price\": 5, \"ingredients\": [\"Mozzarella\", \"pomodoro\", \"basilico\"]}" --user admin:admin -H X-BAASBOX-APPCODE:1234567890 http://localhost:9000/admin/asset

File Asset:

curl --form [email protected] --form name=fileAsset --form meta="{\"name\": \"Margherita\", \"price\": 5, \"ingredients\": [\"Mozzarella\", \"pomodoro\", \"basilico\"]}" --user admin:admin -H X-BAASBOX-APPCODE:1234567890 http://localhost:9000/admin/asset

Note: in this case the file pizza.jpg is a file that must be into the same directory in which you run the command

Retrieve all the assets

GET /admin/asset

Headers: See the General Remarks. The user must be an administrator

Description: This API returns a JSON describing all the available assets

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 403: the user is not an Admin

• Code 200: OK. A JSON collection is provided

6.1. REST API 53

Page 58: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Delete an asset: DELETE /admin/asset/:name

Headers: See the General Remarks. The user must be an administrator

Description: This API deletes a given asset.

Parameters

• name: the name of the asset

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 403: the user is not an Admin

• Code 200: OK. The asset has been deleted.

Resize image

Remark: These APIs work only if the parameter asset is an image

Resize the image with a fixed width and height:GET /asset/:name/resize/:w/:h

Headers: See the General Remarks. The user must be an administrator

Description: Resize image with a specified width and height

Parameters:

• name: name of image

• w: width desired

• h: height desired

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 503: the server is too busy, operation not performed.

• Code 403: the user is not an Admin

• Code 404: asset not found

• Code 200: ok and returns the image resized

Resize the image with a fixed percentual:GET /asset/:name/resize/:perc

Headers: See the General Remarks. The user must be an administrator

Description: Resize image with a specified percentual

Parameters:

• name: name of assets

• perc: percentual for the image resized

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

54 Chapter 6. RestAPI

Page 59: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

• Code 403: the user is not an Admin

• Code 404: asset not found

• Code 200: ok and returns the image resized

Apply a resizeId:GET /asset/:name/resizeId/:sizeId

Headers: See the General Remarks. The user must be an administrator

Description: applies a resizing which is specified in the settings for the admin dashboard, according to the index thatwas set as a parameter. For example: if the settings are [10%,25%,50%,75%] and you use the following API GET/asset/test/resizeId/1, the name test image will be scaled by 10%

Parameters:

• sizeId: the resizing index to be applied.

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 403: the user is not an Admin

• Code 404: asset not found

• Code 200: ok and returns the image resized

Application Settings

These APIs can be used to set some internal settings.

Note that many of these settings are App-related and do not affect server behavior or configuration (like for examplethe listening port). Server related settings must be configured via configuration file, or by hacking the start script.

System Metrics

By calling these APIs it is possible to retrieve information about the system and its resources usage

Retrieve some system statistics: GET /admin/dbStatistics

Headers: See the General Remarks

Description: Returns a set of statistics about DB and memory usage. User must belong to the Admin Role

Returns:

• Code 400: the X-BAASBOX-APPCODE contains an invalid application code

• Code 500: the servers cannot fulfill the request, an internal server error occurred

• Code 403: the user is not an Admin

• Code 200: OK: JSON object and statistics

6.1. REST API 55

Page 60: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

56 Chapter 6. RestAPI

Page 61: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

CHAPTER 7

SDK

Contents:

7.1 SDK

7.1.1 iOS

iOS SDK

Blocks format

There are three block types used throughout the iOS SDK. Each contains an NSError as the second parameter. Thefirst parameter is the result of the HTTP operation. There are three types of results:

• Object: single object already populated by parsing the JSON

• Array: array of objects of the same type you have requested.

• Boolean: boolean value returned by a YES or NO query

Here is the typedef definition

typedef void (^BAAArrayResultBlock)(NSArray *objects, NSError *error);typedef void (^BAAObjectResultBlock)(id object, NSError *error);typedef void (^BAABooleanResultBlock)(BOOL success, NSError *error);

This is a quick example of how to load a set of files.

[BAAFile getFilesWithCompletion:^(NSArray *objects, NSError *error) {

if (error == nil) {// deal with returned pictures

} else {// deal with error

}

}];

This returns an array of objects of the BAAFile class and an error. The suggested pattern within the block is tomanipulate returned data if the error is nil, and to deal with the error otherwise.

57

Page 62: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Authentication

Login To login you need an instance of BAAClient as follows

BAAClient *client = [BAAClient sharedClient];[client authenticateUser:@"user"

password:@"password"completion:^(BOOL success, NSError *error) {

if (success) {// login successfull

} else {// show error

}

}];

Notice that the authentication token for the logged in user is parsed and stored automatically. To access the currentlylogged user you can use this code snippet.

BAAClient *client = [BAAClient sharedClient];client.currentUser

This will return an instance of BAAUser.

Signup If you want to create a new account this is the way.

BAAClient *client = [BAAClient sharedClient];[client createUserWithUsername:@"user"

password:@"password"completion:^(BOOL success, NSError *error) {

if (success) {// signed up

} else {// display error

}

}];

Like in the login API, data related to the currently logged users are available as a property of the BAAClient class.

BAAClient *client = [BAAClient sharedClient];client.currentUser

Users

On the backend each user has four fields by default: visibleByTheUser, visibleByFriends,visibleByRegisteredUsers, visibleByAnonymousUsers. These fields are automatically populated bythe SDK when the JSON is retrieved.

Fetch users

You can load a list of registered users on the backend using the following method.

58 Chapter 7. SDK

Page 63: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

[BAAUser loadUsersWithParameters:nilcompletion:^(NSArray *objects, NSError *error) {

if (error == nil) {// deal with users array

} else {// show error

}

}];

The block will include an array of BAAUser instances or an error. You can provide parameters for pagination. Hereis an example that fetches the first 20 users.

[BAAUser loadUsersWithParameters:@{kPageNumber : @0, kPageSize :@20}completion:^(NSArray *objects, NSError *error) {

// ...

}];

Fetch user details

To retrieve the details of a single user you can use the following method

[BAAUser loadUserDetails:@"cesare"completion:^(BAAUser *user, NSError *error)completion {

if (error == nil) {// deal with user

} else {// show error

}

}];

Fetch users the logged in user is following

BaasBox has the follow/unfollow functionality built in. To retrieve the list of people followed by the logged in useryou can use this method.

BAAUser *user = ...;[user loadFollowingWithCompletion:^(NSArray *following, NSError *error) {

if (error) {// deal with retrieved list

} else {// show error

}}];

The array is populated with instances of BAAUser.

Fetch the followers of the logged in user

To retrieve the followers the logged in user you can use this method.

7.1. SDK 59

Page 64: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

BAAUser *user = ...;[user loadFollowersWithCompletion:^(NSArray *followers, NSError *error) {

if (error) {// deal with retrieved list

} else {// show error

}}];

Follow

The currently logged user can follow another user via this method.

BAAUser *userToBeFollowed = ...;[BAAUser followUser:userToBeFollowed

completion:^(BAAUser *user, NSError *error) {

if (error == nil) {// deal with user

} else {// show error

}

}];

Unfollow

The currently logged in user can unfollow another user via this method.

BAAUser *userToBeUnfollowed = ...;[BAAUser unfollowUser:userToBeUnfollowed

completion:^(BOOL success, NSError *error) {

if (success) {// update UI

} else {// show error

}

}];

Objects

Subclassing BAAObject

You can create custom objects in your app by subclassing BAAObject. Here is an example of a custom classrepresenting a post with two custom properties: a title and a body.

// SMPost.h@interface SMPost : BAAObject

@property (nonatomic, copy) NSString *postTitle;@property (nonatomic, copy) NSString *postBody;

60 Chapter 7. SDK

Page 65: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

@end

// SMPost.m#import "SMPost.h"

@implementation SMPost

- (instancetype) initWithDictionary:(NSDictionary *)dictionary {

self = [super initWithDictionary:dictionary];

if (self) {

_postTitle = dictionary[@"postTitle"];_postBody = dictionary[@"postBody"];

}

return self;

}

- (NSString *)collectionName {

return @"document/posts";

}

@end

There are two key methods to override. The first is initWithDictionary:, in which you should populate theobject with the properties you have added in the header. The second is collectionName and should return the paththat points to the collection on the back end. The SDK takes care of JSON serialization and deserialization of yourcustom class.

Note: when the SDK serializes a custom class to JSON it will use the same property name that you have specified inthe code. For example the SMPost class will be serialized like this:

{"postBody": "Body of post","postTitle": "My title"

}

Fetching objects

You can retrieve a list of custom objects this way.

[SMPost getObjectsWithCompletion:^(NSArray *objects, NSError *error) {

if (error == nil) {// show objects

} else {// show error

}

}];

7.1. SDK 61

Page 66: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

As you can see this is a method of a custom class inherited from BAAObject. This means that the instances in theobjects array are of the same class (SMPost in the example). This call uses default parameters for pagination. If youwant to specify parameters in the query you can use the following method

[SMPost getObjectsWithParams:@{kPageNumber : @0, kPageSize : @20}completion:^(NSArray *objects, NSError *error) {

if (error == nil) {// show objects

} else {// show error

}

}];

This retrieves the first 20 objects of class SMPost stored on the back end.

Saving an object

Once you have an instance of a custom object you can save it this way.

SMPost *post = ...;[SMPost saveObject:post

completion:^(SMPost *savedPost, NSError *error) {

if (error == nil) {// deal with savedPost

} else {// show error

}}];

The saveObject:completion: automatically manages if an object is “new” (not yet saved on the back end) orsimply needs to be updated. In both cases it will return a new instance that you can manipulate within the block.

Deleting an object

To delete an object you can use the following method.

SMPost *postToBeDeleted = ... ;[SMPost deleteObject:postToBeDeleted

completion:^(BOOL success, NSError *error) {

if (success) {// post deleted

} else {// show error

}

}];

62 Chapter 7. SDK

Page 67: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Files

Initializing a BAAFile instance

The BaasBox SDK supports file upload and download. To manipulate a file you use the BAAFile class. To initializean instance you need NSData. For example, if you want a BAAFile to represent an image you can do as follows.

UIImage *image = ...;NSData *data = UIImageJPEGRepresentation(image, 1.0);BAAFile *file = [[BAAFile alloc] initWithData:data];file.contentType = @"image/jpeg";

Both data and content type are fundamental for the upload to succeed.

Uploading a file

To upload a file you can use this method.

[file uploadFileWithCompletion:^(BAAFile *picture, NSError *error) {if (error == nil) {

// upload successful} else {

// show error}

}];

You can attach metadata to a file before uploading it. Each instance of BAAFile has a handy property namedattachedData (it’s an NSMutableDictionary) that allows you to store whatever you like. Here is a short example.

[file.attachedData setObject:@"My title"forKey:@"title"];

[file.attachedData setObject:@[@"spring", @"outdoor"]forKey:@"tags"];

[file.attachedData setObject:@{@"key" : @"value"}forKey:@"dict"];

The data in this property will be retrieved whenever you load the file from the back end.

Downloading a file

To load a file you can use this method.

BAAFile *file = ...;[file loadFileWithCompletion:^(NSData *data, NSError *error) {

if (error == nil) {// deal with data

} else {// show error

}

}];

7.1. SDK 63

Page 68: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

ACL on files

When you have uploaded a file you can grant access to other users. Here is the method.

BAAFile *file = ...;[uploadedPicture grantAccessToRole:kAclRegisteredRole

ofType:kAclReadPermissioncompletion:^(id object, NSError *error) {

if (error == nil) {// ok

} else {// error

}}];

You can specify one of the following types of roles:

• kAclAnonymousRole, publicly visible

• kAclRegisteredRole, visible by whoever has an account on the back end

• kAclAdministratorRole, visible only by the administrator

Permissions are represented by the following constants:

• kAclReadPermission, permission to read a file

• kAclDeletePermission, permission to delete a file

• kAclUpdatePermission, permission to update a file

7.1.2 Android

User Guide Android

The Baasbox Android SDK is meant to get you quickly started in performing CRUD operations on your custom dataobjects. The goal of this guide is to illustrate the essential steps to build your first application in five minutes. Let’s getstarted!

Download the latest version of Android SDK here

Authentication

The first step of each application is to login or signup a new user. Once you have imported the SDK into your project,you can login using the following code snippet.

LoginTask loginTask = new LoginTask();loginTask.execute(username, password);

// Login task definitionpublic class LoginTask extends AsyncTask<String, Void, BAASBoxResult<Void>> {

@Overrideprotected void onPreExecute() {

// update UI if needed, e.g. disable login button}

64 Chapter 7. SDK

Page 69: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

@Overrideprotected BAASBoxResult<Void> doInBackground(String... params) {

return App.bbox.login(params[0], params[1]);}

@Overrideprotected void onPostExecute(BAASBoxResult<Void> result) {

// update UI if neededonLogin(result);

}}

Notice that the information about the user (e.g. username and authentication token) is automatically saved by the SDK.After this call is successful you are good to go and make authenticated calls, like loading or creating new items.

Sign up

Using the SDK you can also allow the creation of new users. The pattern is pretty similar to the login. Here is anexample.

SignupTask signupTask = new SignupTask();

JSONObject user = new JSONObject();

try {user.put("username", username);user.put("password", password);

} catch (JSONException e) {throw new Error(e);

}

signupTask.execute(user);

// SignupTask definitionpublic class SignupTask extends AsyncTask<JSONObject, Void, BAASBoxResult<Void>> {

@Overrideprotected void onPreExecute() {

//Update UI before execution}

@Overrideprotected BAASBoxResult<Void> doInBackground(JSONObject... params) {

return App.bbox.signup(params[0]);}

@Overrideprotected void onPostExecute(BAASBoxResult<Void> result) {

//Update UI after execution}

}

Whenever you need to know if you are authenticated you can use the following code.

App.bbox.isUserLoggedIn();

7.1. SDK 65

Page 70: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Creating and saving objects

To save instances on the server you use the createDocument method of App.bbox, For example, this code snippetadds an entry to an address book.

AddTask addTask = new AddTask();addTask.execute(name, phone);

// AddTask definitionpublic class AddTask extends

AsyncTask<String, Void, BAASBoxResult<JSONObject>> {

@Overrideprotected BAASBoxResult<JSONObject> doInBackground(String... params) {

JSONObject person = new JSONObject();

try {person.put("name", params[0]);person.put("phone", params[1]);

} catch (JSONException e) {throw new Error(e);

}

return App.bbox.createDocument("address-book", person);}

@Overrideprotected void onPostExecute(BAASBoxResult<JSONObject> result) {

// refresh UI to show newly added person}

}

Notice that “address-book” in this example has to match the name of the collection that you have set up on the backend.

Deleting objects

To delete an existing object on the back end you can use the following snippet.

// entry is a json object representing an entry in the address bookadapter.remove(entry);new DeleteTask().execute(entry);

// Delete task definitionpublic class DeleteTask extends

AsyncTask<JSONObject, Void, BAASBoxResult<Void>> {

@Overrideprotected BAASBoxResult<Void> doInBackground(JSONObject... params) {

return App.bbox.deleteDocument("address-book", params[0].optString("id"));}

@Overrideprotected void onPostExecute(BAASBoxResult<Void> result) {

onPersonDeleted(result);}

}

66 Chapter 7. SDK

Page 71: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

Loading objects

To load a collection of objects you just getAllDocuments() as follows.

LoadTask loadTask = new LoadTask();loadTask.execute();

public class LoadTask extendsAsyncTask<Void, Void, BAASBoxResult<JSONArray>> {

@Overrideprotected void onPreExecute() {

// update UI before loading}

@Overrideprotected BAASBoxResult<JSONArray> doInBackground(Void... params) {

return App.bbox.getAllDocuments("address-book", "name ASC", -1, -1);}

@Overrideprotected void onPostExecute(BAASBoxResult<JSONArray> result) {

// update UI after loading}

}

The first parameter of getAllDocuments is again the exact name of the collection set up on the server. The secondis the sorting parameters. The third is the number of the page you’d like to load (-1 to not specify any) and the fourthis the number of results per page.

7.2 Tutorial

BaasBox created tutorials to understand better the features offered.

• Deploy BaasBox on Openshift

• Social Login

• Push Notifications

• Working with assets

List of all available tutorials

7.3 Hacking

You can override many default values and options by providing them to the JVM. To do so, you have to use the -Dparameter in this way

./start -DBAASBOX_PARAMETER=NEW_VALUE

Where BAASBOX_PARAMETER is the key of the parameter to override and NEW_VALUE is the value you wantto use. Please note that there is no space between the D and the name parameter. Overridable keys are:

Regarding the config.file key, a possible example of an external configuration file may be:

7.2. Tutorial 67

Page 72: baasbox Documentation - Read the Docs · – Push notifications for iOS and Android devices •DB management: – Backup/restore and reset of the integrated database 7. baasbox Documentation,

baasbox Documentation, Release 0.7.3

include classpath("application.conf")application.code="1234-56789"orient.baasbox.path=db/baasboxlogger.application=DEBUG

7.3.1 The Play! Framework

BaasBox is built on top of Play! Framework. Because of this you have to download a JDK 6 or above N.B.(JDKnot JRE!) and Play! 2.1.1 at this link, and install them following their installation guides. You must also downloadthe BaasBox source code source from its GitHub Repo. Once all the required software is correctly installed, and theBaasBox source code is in a convenient directory, go to that directory and type play dist

After a while, Play! ends to build the application and a new ./dist directory is created in the unzipped BaasBox sourcecode path. In the new ./dist directory you will find a zip file containing the compiled code. To test it, unzip it in anydirectory and type ./start (remember to set the execution flag). If you are using a Windows system, you need a .bat file.Just create a new start.bat file and place the following line in it:

java %1 -cp ./lib/\*;play.core.server.NettyServer.

(Pay attention to the final dot)

Since BaasBox is based upon the Play! Framework 2.1, many configuration options available by Play! could be usedwith BaasBox. Please refer to the Play! documentation to know how to perform such operations and to customize thedefault behavior.

68 Chapter 7. SDK