NoSQL, No Problem!

 
LeeHicksYou may have already seen that DreamFactory Service Platform (DSP) supports SQL databases with its REST API, but did you know that we also support most of the popular NoSQL databases? Currently, DSPs support Amazon Web Services’ SimpleDB and DynamoDB, Windows Azure’s Tables, MongoDB, MongoHQ, and CouchDB.

While the technology behind, and the interface in front of, each of these services vary, some dramatically, they each support storing data and lots of it. Some already have a REST or somewhat  REST-like HTTP interface to access them, which may mean storing your access keys or authorization information on the client and passing them along with every call. Some do not have an HTTP interface at all and must be accessed through server-side code that you have to go find and install or write yourself. Some allow you to design the primary keys or indexes of your storage tables, some do not. Some support JSON natively, some do not. In fact, the formats supported for data entry and retrieval (think filtering) vary almost as widely as the number of vendors. Get the drift? Different creators, different creations. But you say “I just want a simple way for my app to get my data in and out, quickly and easily.” That’s where I think we can help.

NoSQL as a Service

DSP Services allow you to “on-board” web-based or locally running services that you want to use from your app and access from one authenticated REST API. The access to these services can be controlled by app and by user role. There is more on this and how to provision these services in our documentation here.

The same goes for the supported NoSQL services. We securely store any credentials required to access your storage on the server-side, relieving your app from maintaining it. We remove any cross-site hoops your app would have to handle by making it a “native” REST service on the DSP. We even go a step further and provide a common, fully REST-based API to each of the supported NoSQL service types and use a common data format layout, using JSON, for data entry and retrieval. Where we were able, we also provide a common SQL-like filtering language, making it dirt simple to find the data you need.

We like to call this our “blend layer”. The idea is, just like a DAO (data access object), we simplify the process to use your data. In fact, we have made this so “blended” it is nearly identical to our SQL DB REST API, which we think is powerful but simple to use. So how does this help you? Well, you write the app once, and store your data in your favorite storage. If or when your “favorite” storage changes (i.e. if something cheaper or faster comes along), your app and data will only require minor changes (if any) to keep chugging along.

So what does this wonderful interface look like? Well, since you asked so nice and all. Once you get your service setup on your DSP (using the documentation mentioned earlier, or the vendor-specific follow-up blogs to this blog), you can use our Live API documentation interface to see how it works. Of course, you can use cURL or your favorite REST testing browser app, it is up to you. Since I am such the promotionalist, I’ll use the Swagger interface in this blog to show you.

As with the other DSP services, we put a mostly standard meaning to the HTTP verbs in our REST API. Here is the how they are used for NoSQL services (using “mongo” as our demo service).

DreamFactory MongoDB Rest API

Note that the ‘POST’ is used for creating new entities, ‘PUT’ is used for replacing the whole content of an entity and ‘PATCH’ is used to merge in changes to an entity (‘PATCH’ and ‘MERGE’ HTTP verbs are used interchangeably in the REST API). Also, as with the other DSP services, if your transport layer only accepts ‘GET’ and ‘POST’ verbs, using a ‘POST’ command while setting either a url parameter, ‘method=PATCH’, or a header, X-HTTP-Method = PATCH will “tunnel” the command through properly.

Table Administration

Azure calls them “tables”. So does AWS, that is for DynamoDb, but for SimpleDb, they are called “domains”. For CouchDb, they are called “databases”, not to be confused with MongoDb’s “databases” which house what they call “collections”. See what I mean?? While each vendor calls them something different, we will refer to them collectively as “tables”. These are the things that group your sets of data together or partition them, however you see it. You can actually manage most aspects of the table administration through the REST API.

To get a list of currently available tables, just send a GET request to the service’s root, which, if you are using one of our free-trial DSPs, looks like this.

https://dsp-mydspname.cloud.dreamfactory.com/rest/my_service_api_name_here

Every DSP service, when queried at its root with no extra url parameters, returns an array of resources available by that service. In the SQL and NoSQL case, these resources are table names.

{
   "resource": [
      {
         "name": "test"
      },
      {
         "name": "zipcodes"
      }
   ]
}

To include vendor-specific table information, if any is available, you can send ‘include_properties=true’ as a url parameter in the request. You can also limit the returned data by specifying the tables by name, using the ‘names=table1,table2,table3’ url parameter. The returned data will include a table array, where each object in the array includes at least the ‘name’ field and value, as well as, any available vendor-specific properties of the table, i.e. keys, etc.

https://dsp-mydspname.cloud.dreamfactory.com/rest/mongo?include_properties=true&names=test%2Cuploads
{
   "table": [
       {
           "name": "test",
           "indexes": [
               {
                   "v": 1,
                    "key": {
                       "_id": 1
                   },
                   "ns": "test.test",
                   "name": "_id_"
               }
           ]
       },
       {
           "name": "uploads",
           "indexes": []
       }
   ]
}

Use this same data format for creating new tables, or updating and deleting existing tables. You can also use the ‘names’ url parameter in a delete request to delete existing tables.

Record Administration

Again, whether they are called “entities”, “documents”, or “items”, we collectively call them “records”. These are the groups of name-value pairs that make up your app’s data. The DSP REST API provides the following ways for your app to retrieve, create, update and delete data from the tables.

Retrieving Records

When it comes to making your NoSQL data available to your app, our REST API provides several different methods to get just the data sets you want, when you want it. Here are the available options for a GET request on a particular table.

table get request

The table name is sent as part of the url, while the other options are sent as url parameters. If url parameters are not your cup of tea, you can send most of them as posted data (using POST request with X-HTTP-METHOD = GET as mentioned earlier. Note that the “record” parameter can only be sent in this way.). Most of them are self explanatory, but a few may need clarification.

  • ids” – This is a comma delimited list of unique identifiers (think primary key) values for retrieving multiple records at a time. If passed as POST data, this can also be an array of ids. In the case where they is no static identifier field (DynamoDb), use  of the “id_field” parameter is necessary to indicate which field these values belong to.
  • filter” – This is where you use our simple SQL-like filter string. Comparison operators supported on every platform are ‘ = ‘, ‘ != ‘, ‘ > ‘, ‘ >= ‘, ‘ < ‘, ‘ <= ‘; or as their SQL short form ‘ eq ‘, ‘ ne ‘, ‘ gt ‘, ‘ ge ‘, ‘ lt ‘, ‘ le ‘. Depending on the db vendor, others such as ‘ contains ‘, ‘ like ‘, and ‘ begins_with ‘. Spaces surrounding the operator is required. String values on the right side of the comparison must be within single of double quotes. Depending on the db vendor, logical comparisons (AND, OR, NOT) are also supported. More on the differences in later blogs. The whole filter string must be url-encoded.
  • record” – Used only in POST data, this option allows you to send partial (minimally the identifier fields) or complete records back to the database to be “refreshed” with the latest values. This is also helpful in instances where the table has multiple indexes, i.e. DynamoDb and Azure Tables.

For example, if we want to find the first 3 records in the zipcodes table information that have a population of over 20,000 people, returning only the city, state and percentage over 40 years of age. If you are familiar with SQL, this would look like “SELECT city,state,PopulationOver40 from zipcodes WHERE pop > 20000;”. Here is what it looks like in our REST API.

https://dsp-mydspname.cloud.dreamfactory.com/rest/mongo/zipcodes?filter=pop+%3E+20000&limit=3&fields=city%2Cstate%2CPopulationOver40

And this is what gets returned…

{
 "record": [
   {
     "_id": "28659",
     "city": "NORTH WILKESBORO",
     "state": "NC",
     "PopulationOver40": 9.19
   },
   {
     "_id": "31201",
     "city": "HUBER",
     "state": "GA",
     "PopulationOver40": 99.877
   },
   {
     "_id": "71291",
     "city": "WEST MONROE",
     "state": "LA",
     "PopulationOver40": 80.099
   }
 ]
}

Creating Records

Use this same data format above for creating new records. One could post an array of records, or a single record like this…

POST https://dsp-mydspname.cloud.dreamfactory.com/rest/mongo/zipcodes
   {
     "_id": "29684",
     "city": "STARR",
     "state": "SC",
     "pop": 2889,
     "PopulationOver40": 82.4
   }

If the DB vendor does not automatically create the primary key, it must be included in the POST request. The applicable keys are always returned for successfully created records on a create request.

Updating and Merging Into Records

The same array of records or a single record format with changes is supported for updating records. Using the PUT HTTP verb as mentioned above will replace the whole record with the posted data if found by matching identifiers in the record.

PUT https://dsp-mydspname.cloud.dreamfactory.com/rest/mongo/zipcodes
   {
     "_id": "29684",
     "city": "STARR",
     "state": "SC",
     "pop": 2890,
     "PopulationOver40": 79.4
   }

If you only want to merge changes into a record without having to reset everything, then use the MERGE or PATCH HTTP verb and send only the changes along with the identification fields.

PATCH https://dsp-mydspname.cloud.dreamfactory.com/rest/mongo/zipcodes
   {
     "_id": "29684",
     "pop": 2890,
     "PopulationOver40": 79.4
   }

If you only want to update or merge data for one record, and it can be identified by a single key field, then you could also add the id to the end of the url, and pass only the fields that require change.

PATCH https://dsp-mydspname.cloud.dreamfactory.com/rest/mongo/zipcodes/29684
   {
     "pop": 2890,
     "PopulationOver40": 79.4
   }

Two other methods of merging data are by id list or filter (using “ids” or “filter” url parameters mentioned above for retrieving records). In these cases, if not natively supported, the server will query the table for the filtering results, merge in the record changes and push the changes back in an update request. This is an easy way of updating multiple records with the same field-value changes.

Deleting Records 

Deleting is similar to updating records but no posted data is required.

More to Come…

Stay tuned for a series of blogs on each of the supported NoSQL services and how to use them in your next awesome app.

Getting Started with the DreamFactory API

 

JasonSykesIn this blog post, we’ll show you how to make some simple API calls with the DreamFactory API. The API requires SSL3. If you plan on making requests from cURL, or your native SDK, make sure you are using version 3.

For example, in cURL:

curl -3 url

Your “api key” to talk to our API is your App Name as defined in the DreamFactory Administration Console. For each request, you can:

  1. Append app_name=yourappname to the query string or
  2. Send a request header called X-DreamFactory-Application-Name with the value of your app name

Working with User Sessions (/user/session)

Authentication 

If your application is not part of the guest user’s role, then access to any service or data components will require authentication. To authenticate a user, simply POST a JSON string to /user/session that takes on the following format:
{“email”:”email_value”, “password”:”password_value”}
For example:
curl -k -3 -X POST https://dsp-yourdsp.cloud.dreamfactory.com/rest/user/session -H "X-DreamFactory-Application-Name: todojquery" -d "{ \"email\" : \"[email protected]\", \"password\" : \"foo\" }"
This will return one of four responses:  
  • A 201 as the session has been created. In the response, you’ll see a session_id has been created. Very Important: For all future requests to the API, you’ll need to pass this value as a new request header called X-DreamFactory-Session-Token
 
  • A 401 if the login information did not match any records on the backend
 
  • A 403 if CORS has not been enabled and you’re trying to use the API cross-domain
 
  • A 400 if you did not include your API Key (App Name)           

You can append app_name=yourappname to the query string or send a request header calledX-DreamFactory-Application-Name.

To refresh a user’s session, or just check to see if they have one, simply do a GET on /user/session.

Using our local DB service (/db/[table name]/[id])

As you’d expect, getting to your data is just a URL away. 

Retrieving Data 

To access any table available to your role, use the following format. In this example, we make a request for the todo table:

GET https://dsp-yourdsp.cloud.dreamfactory.com/rest/db/todo
For example:
curl -3 https://dsp-yourdsp.cloud.dreamfactory.com/rest/db/todo?app_name=todoangular

Important Note: Don’t forget your X-DreamFactory-Application-Name, and if a session is required, your X-DreamFactory-Session-Token header.

If you are doing this cross-domain, enable CORS in the System Configuration section of the DreamFactory Administration Console.

Filtering Data

To filter data by field, add an additional url param (filter) as follows. In this example, we make a request for the todo table:

https://dsp-yourdsp.cloud.dreamfactory.com/rest/db/todo?app_name=todoangular&filter=complete=true

This API call returns all todo items that are complete.

Attaching Schema

To attach your table’s schema as metadata in the response, just add a url param, like this:

GET https://dsp-yourdsp.cloud.dreamfactory.com/rest/db/todo?include_schema=true

Important Note: Don’t forget your X-DreamFactory-Application-Name, and if a session is required, your X-DreamFactory-Session-Token header.

Enjoy!  If you have any issues, head over to http://dreamfactorysoftware.github.io

Adding a Remote Web Service to Your DSP

 
ToddAppletonThe DreamFactory Services Platform (DSP) provides a flexible and powerful backend for your mobile apps. If you don’t have a DreamFactory account, sign up here. One of the key features is the ability to integrate any number of remote web services, and access them directly through the DreamFactory REST API. In this blog post we’ll walk through the process of setting up and invoking a remote web service. Continue reading “Adding a Remote Web Service to Your DSP”

SenchaCon, A Look Back

 
ToddAppletonLast week I had the pleasure of attending SenchaCon 2013 in Orlando, FL.  It was four days of fun learning including boot camps, new product announcements, and in-depth sessions on all aspects of Sencha and general web development.  Throughout the conference there were a few recurring themes that I wanted to touch on in this post, and in some cases connect the dots back to our DreamFactory Services Platform (DSP).

HTML5 for Mobile Apps

There was a lot of talk about the future of HTML5 and JavaScript for building mobile apps. The gap between what is possible with native apps vs HTML5 apps is quickly closing. Modern browsers are introducing new API’s and CSS capabilities further lessening the need for native app development. Jacky Nguyen gave a great talk on the making of Fastbook, an HTML5-based clone of the native Facebook app that uses some clever tricks to maximize performance, exceeding that of the native app in most cases. At DreamFactory we think the rich client is the way to go, and HTML5 and JavaScript will be the go-to tools.

REST and JSON Everywhere

This should come as no surprise, but pretty much everyone is expecting to exchange JSON data via a REST API.

Apps for the Enterprise

One of the big announcements last week was the introduction of Sencha Space. It’s intended to address feedback from enterprise customers that they need more than just cool apps. They need the ability to host and manage those apps. They need to control which users can access each app, and have the ability to grant or revoke access by a particular device.  They need the ability to report on usage – who logged in, when, and where. We agree!

Small Teams, Big Apps

I repeatedly saw examples of small, or even one person teams producing quality mobile apps using Sencha technologies. Sencha gave a preview of Architect 3.0 which provides a lot of drag and drop capability for building HTML5 apps, eliminating much of the repetitive code everyone hates to write. In the spirit of single engineer apps,  DreamFactory and Modus Create partnered for an unconference session to demo their Sencha-based address book app running on the DreamFactory backend. The app is a hybrid using either Ext JS or Sencha Touch based on device type.  It was built by a single engineer at Modus Create in just a few weeks with no server side development required. These are just a few of the take aways from SenchaCon 2013. It was a great conference and we’re looking forward to next year!

Four Big Problems DreamFactory Solves

 
BillAppletonThe DreamFactory Services Platform (DSP) solves four big problems that plague mobile application developers. First, we provide an easy to use REST API that covers a wide variety of backend services. Many server side assets like SQL databases don’t have a client addressable API. In cases like this we build out the entire API for the backend system. Other server side assets might have an API, but they don’t support JSON data, so we translate everything into JSON for ease of use. Lastly, different systems from different vendors tend to have wildly different or technically challenging network protocols and authentication methods. Go look at the interfaces for MongoDB, S3, Azure Tables, SimpleDB, SendGrid, MySQL, and CloudFiles. They all work differently. So we simplify all those systems into a single REST API that can be used from the client. Second, we hide the master credentials for all these different systems and expose their functionality through single sign-on with user roles and permissions. This means you never have to store or use a master credential from the client device where it can be stolen by a hacker. Instead you have a single user authenticate in to our service architecture where they are given limited capabilities to read, write, create, or update the various data sources. All of this is controlled by their user role. And if they lose their mobile device the system admin can instantly kill their session, protecting the backend systems. Third, we solve the originating host problem for HTML5 developers. Modern browsers limit web application communication to the originating server. This is a security measure designed to protect private networks behind the firewall. There are some exceptions to the rule, but in general HTML5 applications can always communicate with their originating host, while talking to other networks is problematic. So the DSP provides a single point of communication that combines data sources from other servers. By the way, your DSP also provides extensive application hosting options. Your CSS, HTML, and JavaScript files are stored right on the same platform as the other services for originating host access. If you need to use the REST API from another domain we can also do that with programmable CORs access that can be set up by the administrator. The DSP also makes life easier for native client technologies. When a native client attempts to communicate with a whole bunch of different servers bad things tend to happen. The client must open network communications with each backend system, handle a bunch of authentication protocols, load and manage all the data, handle network errors and latency, etc. This adds a lot of complexity to the application, especially on a mobile device with intermittent connectivity and limited bandwidth. But with a DSP your native client can communicate to a single endpoint and consume a single REST API that combines everything needed for application runtime. Lastly, the DSP provides administration for all of the different users, applications, and services that are needed. You can control which users see which applications, and which applications can use which services. You can use the DSP Admin Panel to create sophisticated user role and permission systems. For example, the sales, marketing, and executive personnel at a company might each log in and see a very different view of the applications and data. For a simpler scenario without a log in, you could create a “read only” user role that delivers all the various documents and database information that the application uses. The only actual user log in would be for the system administrator who curates the media stored on the server. Taken together, these four capabilities form the powerful backbone of the DreamFactory Services Platform. We are working hard to solve these backend problems so that you can focus on the front end. The result is high performance mobile applications written by much smaller development teams with reduced time to value.
http://www.dreamfactory.com

Try our Free Edition right now, or install our Apache License software package on your cloud or data center. Manage your applications with AWS, Azure, Rackspace, or any VM.

Great REST API’s You Can’t Use

 
BillAppletonThe Mongo database has a great REST API, but you can’t use it. They tell you this right in the docs: “Please note that this apiKey will give full access to all data within the databases belonging to your MongoLab account. If you do not have it secured on an app server, someone can gain access to it and your data.” In other words, you must include your API Key in the REST request to connect to your data. So this API cannot be used from a client. In a native application these credentials could be found in the binary source code or sniffed network traffic. In HTML5 someone could simply view the source and grab your master credentials. This API can only be used from a server. The Amazon S3 document storage system also has a REST API, but you can’t use that, either. Here’s how they explain it: “You then use your AWS secret access key to calculate the HMAC of that string… Finally, you add this signature as a parameter of the request by using the syntax described in this section.” In other words the secret key must be used to create each API request. If someone gains access to your secret key then they have access to all of your data. Not just your S3 files, I’m talking about ALL of your Amazon Web Services. Once again, you need a server to use S3 or other Amazon services. What about Windows Azure? Here is how they tell you to create an Azure BLOB or Azure Tables account: “The Create Storage Account operation creates a new storage account in Windows Azure. The Create Storage Account request may be specified as follows. Replace <subscription-id> with your subscription ID in the following URL…” So once again, you cannot use these services from HTML5 or from a native application without fear of having your master account exposed. So you must build a server to use these powerful services. Well, if you’re going to build a server, you might as well build a good one. Here are some of the issues you will probably want to think about: 1) Your server must hide the master credentials to all the remote services you need like MongoDB, S3, and Azure. This way your individual accounts with Rackspace, Amazon, Microsoft, etc. cannot be hacked. 2) Meanwhile, you must provide client access to these services. User management capabilities and single-sign on with password hashing and time sensitive session IDs are the best practice here. Now add powerful CRUD roles and permissions by user to safeguard data access. 3) You don’t want to rebuild your server over and over in the future. You need a comprehensive palette of services for all the modern capabilities you might need such as SQL data, NoSQL data, BLOB storage, application hosting, email, and external services. 4) While you are at it, might as well simplify the wildly different interfaces these guys use to talk to all their different services. Every single one of these beasts will need to be tamed with a simple, clean, easy to use REST interface that supports native JSON objects. 5) Make your service interface lightening fast with carefully optimized code, and then conduct some load testing in the real world with tens of thousands of users. Now you are ready for a security audit. 6) Be sure that you have solved the “originating host” problems for HTML5 users. They will need to access all these services from a single domain. A nice feature to add would be programmatic CORs access so that they could use your services from other domains if needed. So that’s the bad news. In order to use powerful services for your next application you are going to have to build a sophisticated server. But finally, some good news: we have already built this server just for you. The DreamFactory Services platform does all of this stuff. We’ve been working hard on this project for years. You can try it out at our website www.dreamfactory.com or install the open source software package on your favorite cloud for free. There is a REST API for everything you need. In fact you won’t need to do any server side programming at all. Just go write your application. So what are you waiting for?

Demo Screencast – Connect an AngularJS App to the DreamFactory backend

 
BenBusseIn this short screencast we’ll show you how to connect a simple To Do app written in Angular JS to the DreamFactory backend using our REST API with cross-origin resource sharing (CORS) enabled. CORs enables you to develop and test apps in your own local environment that points directly to the DreamFactory backend. Also check out our tutorials for this app written in AngularJS, jQuery and Sencha. Thanks for watching!

Demo – How to Make Relationship Queries with DreamFactory’s REST API

 
BenBusseDevelopers often ask how to query related data with DreamFactory’s REST API. For example, how do you fetch a record and its related children as JSON in a single API call? In this post, we’ll demonstrate related data queries with a real example. Also check out these related blog posts. Why We Like Swagger for API Docs covers how to use our live API docs to explore the API. To learn more about how Modus Create built the Address Book application with DreamFactory, check out the DreamFactory & Modus Create Case Study. 1. To follow along, you’ll first need a DreamFactory account. You can sign up for an account here. 2. Log in to your account, go to your DSP admin console, and click on the Applications tab on the left hand side. Swagger blog 1 3. Click ‘Import New App’ in the upper right corner and choose the Address Book sample app. This contains related schema for both parent-child and related records via junction table relationships. Swagger blog 2 Once you’ve imported the application, you can preview it in your DSP. Swagger blog 3 Use your DSP admin user name and password to log in to the Address Book app and see the app. Swagger blog 4 4. Go to the ‘Manage Schema’ and ‘Manage Data’ tabs to peruse the table layouts and sample data if you wish. Swagger blog 5 The Contacts table stores basic information about each contact. ContactInfo stores contact information like phone, email, and address. A Contact can have many child ContactInfo records. The ContactGroups table stores information about Groups. A Contact can belong to any number of Groups. ContactRelationships is a junction table that stores the associations between Contacts and Groups. Swagger blog 6 5. Click ‘API Documentation’ to load Swagger REST API interface. Swagger blog 7 Select ‘schema’ -> GET /schema/{table_name} to expand. Swagger blog 8 In the ‘table_name’ field type ‘Contacts’ and click the ‘Try it out’ button. Swagger blog 9 In the Response Body, you’ll see the field section and the related objects. Note the relationship names in the JSON (highlighted in red below) and the key value pairs that describe each relationship. Swagger blog 12 6. Back in the main Swagger API Documentation, Select ‘db’ -> GET /db/{table_name}. Swagger blog 10 In the ‘table_name’ field type ‘Contacts’. In the ‘ids’ field enter a couple of ids from the sample data e.g. 1,3). In the ‘related’ field type ‘ContactInfos_by_contactId,ContactGroups_by_ContactRelationships’. This will pull both the child info records and the groups related by junction. Click ‘Try it out’ and note the URL call and results. Swagger blog 11 The Request URLlooks like this, where ‘foo’ is the name of your own DSP. http://dsp-foo.cloud.dreamfactory.com/rest/db/Contacts?ids=1%2C3&related=ContactInfos_by_contactId%2CContactGroups_by_ContactRelationships Take a look at the Response Body and notice the JSON structure for child data, in this example multiple ways to contact a person. Also notice how the JSON encodes the associations between a Contact and zero or more Contact Groups to which the Contact belongs. Swagger blog 13 We hope this overview has shown you how to make sophisticated queries with DreamFactory’s REST API! Please comment if you have any feedback or questions.

jQuery App Tutorial with the DreamFactory REST API

 
ToddAppletonThis blog post is about building a to do list app using the DreamFactory Services Platform (DSP) for the backend. We provide a comprehensive REST API and an easy-to-use JavaScript SDK for making API calls. This example will show you how to authenticate to your DSP and then make simple CRUD calls using the SDK. If you don’t have a DreamFactory account, sign up here. This app is available on new DSP’s as a sample app named “Todo List jQuery w/SDK”. If you don’t have it installed you can import it from GitHub using the apps tab in the admin console.

Code Walkthrough

This app consists of three files plus the SDK. index.html – loads jQuery and Twitter Bootstrap and has a table to hold the list. It has an input field and add button for adding items to the list. app.js – functions for creating, retrieving, updating, and deleting list items and building the list. style.css – simple styling The complete source code for this app is available on GitHub at https://github.com/dreamfactorysoftware/app-todo-jquery.  You can go there to clone this repo to your local machine. In the SDK /lib directory there is a file sdk_init.js. This is where you specify the name of your app and the DSP your app is talking to. For hosted apps that use the DSP for app file storage you could set dsp_url to use location.protocol and location.host and it would always init the SDK to use the “current” DSP. If not a hosted app then dsp_url should be set to the DSP you want to use for that app. When the SDK has been initialized the ‘apiReady’ event is triggered. At that point the app is ready to make API calls. The first thing we should do is check for a valid session and, if none exists, try to log in. The doLoginDialog() and login() methods take care of this.
$(window).on("apiReady", function () {

    checkSession();
});

function checkSession() {

    $("#loading").show();
    // check for existing session, relevant when code is hosted on the dsp
    window.df.apis.user.getSession({"body": {}}, function (response) {
        $("#loading").hide();
        // existing session found, assign session token
        // to be used for the session duration
        var session = new ApiKeyAuthorization(
            "X-Dreamfactory-Session-Token",
            response.session_id,
            'header');
        window.authorizations.add("X-DreamFactory-Session-Token", session);
        runApp();
    }, function (response) {
        $("#loading").hide();
        // no valid session, try to log in
        doLogInDialog();
    });
}
After a session has been established we call runApp() which is the main entry point into the app. The function getRecords() uses the SDK to retrieve all records from the database table named todo. You could easily use NoSQL storage such as MongoDB by adding it as a new service on your DSP, then changing df.apis.db to df.apis.mongodb in each SDK call.
function runApp() {

    // your app starts here
    getRecords();
}

function getRecords() {

    window.df.apis.db.getRecords({"table_name":"todo"},
    function (response) {
        buildItemList(response);
    }, crudError
    );
}
}
On success, an array of records is returned such as
{
   "record":[
      {
         "id":"35",
         "name":"item 1",
         "complete":false
      },
      {
         "id":"36",
         "name":"item 2",
         "complete":true
      },
      {
         "id":"38",
         "name":"item 3",
         "complete":false
      }
   ]
}
buildItemList() uses this array to populate a table inside the list-container div. Column 1 of the table is for the delete icon. Column two is for the item name. The id of each item is stored in data-id and used when the item is updated or deleted. Note the onclick handlers being set up for the update and delete ui elements. This is where the completion is toggled.
function buildItemList(json) {

    var html = '';
    if (json.record) {
        json.record.forEach(function (entry) {
            var name = entry.name;
            var id = entry.id;
            html += '';
            html += '';
            if (entry.complete === true) {
                html += '' + name + '';
            } else {
                html += '' + name + '';
            }
            html += '';
        });
    }
    $('table').html(html);
    $('#list-container .item').click(function (e) {
        var id = $(this).data('id');
        var complete = $(this).hasClass('strike');
        updateRecord(id, !complete);
    });
    $('#list-container i').click(function (e) {
        var id = $(this).data('id');
        deleteRecord(id);
    });
}
When you enter a new item and click the Add Item button, the function createRecord() is called. It grabs the item name from the input field and, if not empty, calls the SDK createRecords() method. The POST data is passed in as the “body” field and is an array of JS objects. In this case there’s only one element in the array. Since it’s a new item we will set the complete field to false. On success the input field is cleared and the list is rebuilt. To keep things as simple as possible we are calling getRecords() to retrieve and rebuild the entire list rather than updating the DOM with only the items that changed.
function createRecord() {

    var name = $('#itemname').val();
    if (name === '') return;
    var item = {"record":[
        {"name":name, "complete":false}
    ]};
    df.apis.db.createRecords({"table_name":"todo", "body":item},
    function (response) {
        $('#itemname').val('');
        getRecords();
    }, crudError
    );
}
You can click an item in the list to toggle its completion status. Each time you do this the function updateRecord() will be called. It calls the SDK method mergeRecords() with body containing an array of records to be updated. The database id must be included for each record being updated.
function updateRecord(id, complete) {

    var item = {"record":[
        {"id":id, "complete":complete}
    ]};
    df.apis.db.mergeRecords({"table_name":"todo", "body":item},
    function (response) {
        getRecords();
    }, crudError
    );
}
You can click the minus button next to an item to delete it from the list. Each time you do this the function deleteRecord() will be called. It calls the SDK method deleteRecords() with the ids field containing a comma-delimited list of ids to delete.
function deleteRecord(id) {

    df.apis.db.deleteRecords({"table_name":"todo", "ids":id},
    function (response) {
        getRecords();
    }, crudError
    );
}
Hopefully this gives you a basic understanding of how to use the SDK for CRUD operations. You can experiment directly with the API using the Live API Docs tab in the admin console of your DSP. You can use your developer tools to examine each API request in detail. Please post any questions or comments and we’ll get back to you.

Mobile App Development with CORs and Pub/Sub

 

JasonSykesThe ability to build apps from your desktop or local server is a huge plus for developers using their own debug tools, test suites, etc. With our latest Version 1.0.4 release, we now support these use cases plus the ability to run apps from outside of your DSP and still enjoy the flexibility of our REST API.

Simply log in to your DSP and click on the System Config menu item on the left hand side. On the System Config screen you’ll see the CORS Access options. Setting * will allow you to work from your desktop or anywhere. You may also use your localhost server, or another DSP or remote server you wish to have access to your data or service. Having the allowed verbs checkboxes enforces another layer of access control by locking down the entire DSP to use only the verbs checked for CORS. A future release will have CORS Access specifiable per application.

To use CORS without logging in, you’ll also have to allow for Guest Access, and create a Role for guest user access. This way you can limit any guest access to only database tables or services you see fit.

system config

If you’d like to pass authentication instead of having a guest role, consult our Swagger API docs here for the latest API call for logging in a user (see the /user/session POST request). That POST will return a session_id that you can pass as a new header called X-DreamFactory-Session-Token with all your future API requests. You will also need to include the API name you created with your application as X-DreamFactory-Application-Name if you haven’t already.

We’ve also added live data through a new publication / subscription framework.

We’re using Faye running on Node. Check here for the Faye documentation as well some good advice on security.

Need to see it working? Here’s a Plunker showing our Angular Todo Application using CORS and PubSub to talk to our demo server.

To see pub/sub working on it’s own, try this real time chat app on Plunker

Enjoy! And as always, if you have any questions, please contact us!