Parse.com - dynamic data storage for mobile

This post is more than 2 years old.

Updated September 3, 2012: As just an FYI, since I wrote this post Parse launched a JavaScript API. I'd recommend using that instead of the REST-based API if you are using JavaScript. You can still use the REST-based API, but using their JS API let's you skip some of the authorization issues I had below.

During the Christmas break, I had the chance to look at, and play with, Parse. While you can check the site for the marketing description, the basic idea behind the service is a way to store data for mobile applications without the need for a server. I played with their API and was incredibly impressed by what I saw. Here's why you should consider them:

  • First off - you can skip setting up a server. Now, I know that may sound crazy. I use ColdFusion everywhere. Most of us have a web server we can use. But having an ad hoc back end system for your mobile apps is a powerful incentive.
  • Their storage system allows you to store any data. Basically, you can take your JavaScript object, JSON serialize it, and store. While not explicitly called out on their site (or maybe it is, I didn't check every page), they are obviously using some form of NoSQL on the back end.
  • They automatically handle basic metadata for your objects. So no need to worry about a created or updated field. It's a small thing, but darn useful.

Parse has full SDKs for Android and iOS, but even better, they've got a URL based API. You can use this API to create, update, delete, and search your data.

Just to reiterate to make sure this is clear - your mobile applications can make use of a dynamic database without any setup on your web server. Just sign up, get your keys, and get cranking.

Even better, they provide some real good benefits on top of what I already said.

First - any objects you create will have metadata (date+ID) added to them automatically. Yeah you could do that yourself, but it's a handy addition.

Second - they have special support for users. Basically, they recognize that user objects are probably something almost every application has, so they go out of their way to handle them better and make it part of your model.

Third - they also support geolocation searches. I'm not sure how often I'd use this, but if you tag data with a location, they make it trivial to later search for objects within a certain range. I've done this manually a few times in SQL and I can tell you - it's not fun. (Even when cutting and pasting a solution.)

Four - they have a nice web based data browser. This allows you to do some basic CRUD type operations and is real useful while testing:

You can read more about their REST API here. I decided to give their API a try with PhoneGap and jQuery. While Parse is a paid service, they do offer a free version in their pricing plans.

Hitting their API with jQuery proved to be a bit difficult. You need to include a username and password (which corresponds with two of your keys). That parts easy enough if you use $.ajax. What proved more difficult was the Authorization header. This header needs to be the combination of the username/password strings and has to be Base64 encoded.

I found a JavaScript library for this here: http://www.webtoolkit.info/javascript-base64.html.

This worked, but I also discovered that some modern browsers include it natively via window.btoa. I combined this with a blog post by Bruce Kroez to come up with this method:

function make_base_auth(user, password) { var hash = window.btoa(tok); return "Basic " + hash; }

I believe, stress, believe, window.btoa may not work in iOS. If so, switch to the JavaScript library version listed above. So given that, a basic hit to Parse via jQuery could look like so:

var note = { title:"Test title", body:"Test body" };

$.ajax({ contentType:"application/json", dataType:"json", url:ROOT+"classes/note", username:appId, password:masterKey, processData:false, headers:{ "Authorization": make_base_auth(appId,masterKey) }, type:"POST", data:JSON.stringify(note), error:function(e) { alert('error: '+e);} }).done(function(e,status) { alert('Done'); });

In this case, I'm adding an object by doing a POST. Notice how I can just make a note object, serialize it, and send it. I love that. You get a JSON object back containing the ID of the new object. How about listing objects?

$.ajax({ contentType:"application/json", dataType:"json", url:ROOT+"classes/note", username:appId, password:masterKey, processData:false, headers:{ "Authorization": make_base_auth(appId,masterKey) }, type:"GET", error:function(e) { alert('error: '+e);} }).done(function(e,status) { var s = ""; for(var i=0; i<e.results.length; i++) { var note = e.results[i]; s+= "<p><b>id:</b>"+note.objectId+"<br/>"; s+= "<b>created:</b>"+note.createdAt+"<br/>"; s+= "<b>title:</b>"+note.title+"<br/>"; s+= "</p>"; } $("#result").html(s); });

Note that the significant change here was from POST to GET. It's as simple as that. I can then loop over my results and display them how I choose. Note that they support both pagination and getting the total number of results too.

So, how about an application? I wrote a super simple application that let's me add an object by clicking a button and then generate a list. It isn't dynamic at all, but demonstrates the API. jQuery supports an ajaxSetup function which lets me default a lot of the stuff you saw above. First, I built up a super simple HTML page:

<!DOCTYPE HTML> <html> <head>

<meta name="viewport" content="width=320; user-scalable=no" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>PhoneGap</title> <script type="text/javascript" charset="utf-8" src="js/phonegap-1.3.0.js"></script> <script type="text/javascript" charset="utf-8" src="js/jquery-1.7.min.js"></script> <script type="text/javascript" charset="utf-8" src="js/jquery.parse.js"></script> <script type="text/javascript" charset="utf-8" src="js/main.js"></script> <style> input[type=button] { width: 100%; padding: 10px; } </style> </head>

<body onload="init()">

<input type="button" id="addBtn" value="Add Item"><br/> <input type="button" id="listBtn" value="List Items"><br/> <div id="result"></div>

</body> </html>

And then whipped up this JavaScript:

var appId = "f4yClrICW58n0IbryPbFFBC99cZvHUaVI0muEH7d"; var clientKey = "ameusdLfx4Kl4nV316lzMX8Wb0lli4NEpb5GgDXN"; var masterKey = "PiRAKmRtMIaexl4uBlvMDyo6gEUvCpLHpYqOIuJo"; var ROOT = "https://api.parse.com/1/";

$.ajaxSetup({ contentType:"application/json", dataType:"json", username:appId, password:masterKey, processData:false, headers:{ "Authorization": make_base_auth(appId,masterKey) }, error:function(e) { alert('error: '+e);} });

function init() { document.addEventListener("deviceready", deviceready, true); }

function make_base_auth(user, password) { var tok = user + ':' + password; // var hash = Base64.encode(tok); var hash = window.btoa(tok); return "Basic " + hash; }

function deviceready() {

$("#addBtn").on("click", function() {
	//demo adding an item
	var note = {
			title:"Test title",
			body:"Test body"
	};
	
	$.ajax({
		url:ROOT+"classes/note",
		type:"POST",
		data:JSON.stringify(note)
	}).done(function(e,status) {
		alert('Done');
	});
});

$("#listBtn").on("click", function() {
	//demo getting items
	$.ajax({
		url:ROOT+"classes/note",
		type:"GET"
	}).done(function(e,status) {
		var s = "";
		for(var i=0; i&lt;e.results.length; i++) {
			var note = e.results[i];
			s+= "&lt;p&gt;&lt;b&gt;id:&lt;/b&gt;"+note.objectId+"&lt;br/&gt;";
			s+= "&lt;b&gt;created:&lt;/b&gt;"+note.createdAt+"&lt;br/&gt;";
			s+= "&lt;b&gt;title:&lt;/b&gt;"+note.title+"&lt;br/&gt;";
			s+= "&lt;/p&gt;";
		}
		$("#result").html(s);
	});
});

}

Here's a quick screen shot:

As I said, I think this is an incredibly impressive service. The only negative I can see so far is that it seems a bit slow, but, I only tested with the Android Emulator, and that tends to make everything look a bit slow. I've yet to test it on a real device over WiFi yet.

Also - note that their REST API will also work great with your server applications. Now, I know I just said you don't need a server, but if you want to offload data storage and traffic to Parse, you can use another server to handle things like reporting or management. I tried calling Parse via ColdFusion and it worked well.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Gareth Arch posted on 1/4/2012 at 12:58 AM

Now this is *exactly* what I've been looking for for my mobile apps :)
Thanks Ray!

Comment 2 by Raymond Camden posted on 1/4/2012 at 1:01 AM

I should add - if anyone wants my PhoneGap app, just let me know. I figured it was too trivial to actually share. I see I included my keys in the code above, so, um, that's bad, but it's a demo app, and the company knows about my blog post, so I'm not going to fret about it.

Comment 3 by Tikhon posted on 1/5/2012 at 12:56 AM

I'd like to see the PhoneGap app if you don't mind! We get a ton of requests from PhoneGap and Appcelerator users for Parse integration and maybe you'd let us use your app as an example?

Great blog post Ray -- really impressive.

Best,
Tikhon

Comment 4 by Tikhon posted on 1/5/2012 at 12:56 AM

Oh can you remove my email address from that last comment? :-) Thanks!

Comment 5 by Raymond Camden posted on 1/5/2012 at 1:00 AM

You can download a zip of the Eclipse project here:

http://www.raymondcamden.co...

The APK is in the bin folder. In theory, you can add this to your Eclipse install and run it.

p.s. Will remove your email addy from the comment in a sec.

Comment 6 by Raymond Camden posted on 1/5/2012 at 1:01 AM

If I get time, I'll try to finish my app and turn it into a real mini Notes type app.

Comment 7 by Andrew Gscheidle posted on 1/12/2012 at 12:53 AM

Ray,
I get 404 when trying to download the parse.zip. Is it no longer there? If you can make available, I'd greatly appreciate it!

Comment 8 by Raymond Camden posted on 1/12/2012 at 1:01 AM

oops, change that to parsedemo.zip.

Comment 9 by Andrew Gscheidle posted on 1/12/2012 at 3:07 AM

Ray,
When I try to run a similar app, it gives me problems with trying to call the REST api at Parse because I'm trying to run on a local web server to debug. Did you run into anything similar?

Error:
XMLHttpRequest cannot load https://api.parse.com/1/cla...[objectid]. Origin http://andys-imac is not allowed by Access-Control-Allow-Origin.

*Note, I'm using a real objectId in my code, just don't want to post on here.

Thanks,
Andrew

Comment 10 by Raymond Camden posted on 1/12/2012 at 3:09 AM

That's normal - it's your browser not letting you do a network request to another domain. Some APIs support JSON/P, which is a 'cheat' way around it, but I do not _think_ Parse.com does. You could hit ColdFusion on your local server and have it proxy the request (or PHP, Ruby, etc).

In my testing, I never ran it as a file on my own server. (Well, I did for my ColdFusion test, but that wasn't Ajax.)

Comment 11 by Andrew Gscheidle posted on 1/12/2012 at 4:20 AM

Ray,
Sigh... this is frustrating for sure. When you created your phone gap app, you were running it on a web server, not locally? I suppose I could use dropbox or something as a cheat for a remote host. Hmmm;

Comment 12 by Raymond Camden posted on 1/12/2012 at 4:37 AM

Ah, you have a fundamental misunderstanding of PhoneGap here. PhoneGap packages your HTML/JS/CSS up into a native application. It runs your HTML - much like you can run HTML by just double clicking on an HTML file on your desktop. However, PhoneGap HTML apps are NOT restricted in the same ways traditional HTML apps are. So for example, I can do an Ajax request to _any_ domain. It just plain works.

Does that distinction make sense?

Is it time for me to give a PhoneGap preso over Google+ Hangouts? :)

Comment 13 by Andrew Gscheidle posted on 1/12/2012 at 10:31 PM

Ray,
I tried running this on Apache on my local box (using the built in Apache instance on mac) and that didn't work. Why would CF running locally work any better (just curious). The problem is, when I run this in iOS/Android emulator, the Parse calls fail for apparently the same reason. I'm interested to know more about how you developed your app without running into this. Thanks!

Comment 14 by Raymond Camden posted on 1/12/2012 at 10:33 PM

I think we are still misunderstanding each other.

The CF code wasn't using JavaScript/Ajax to speak to Parse. It just used HTTP.

You can't run my main code above on your web server. It just won't work because of the remote XHR call.

Does that make sense?

Now- when you run this in Android, it _should_ work fine. I've never had issues doing a HTTP call to remove servers. If you could send me your APK, I could take a look.

Comment 15 by Andrew Gscheidle posted on 1/12/2012 at 10:40 PM

My fault for not being clear... I've not run your code, nor tried to. I was referring to my creation of code similar to that shared in the above article.

The article above mentions using AJAX to call the Parse API methods.Your parse demo is entirely html/js, right? At least, the part you made available to download was. So I was wondering how you got an html/jQuery mobile app using Ajax calls to Parse to work in a browser/emulator, etc. Does that make sense?

Perhaps it only works on the physical device. That would really suck and impede one from seriously using Parse.com services in an app. Maybe I'm missing something - it's been known to happen :)

Comment 16 by Raymond Camden posted on 1/12/2012 at 10:41 PM

I didn't use the browser at all. I used either real hardware, or the Android emulator.

Comment 17 by Stelios posted on 2/9/2012 at 3:40 PM

Hi Ray,
Great code! Thanks for your contribution!
I am trying to hit the logging in functionality of Parse using $.ajax (i have already created 2 users via curl) but with no success. Here is sth i tried.

$.ajax({
url:ROOT+"login",
type:"GET",
data:"username=stelios",
data:"password=123456"
}).done(function(e,status) {
alert('Logged in');
});

Could u be of any help?

Comment 18 by Raymond Camden posted on 2/9/2012 at 9:34 PM

The data argument, afaik, should be _one_ object, not multiple keys as you had it there. I'd change it to:

data:{"username":"stelios","password":"123456"}

Comment 19 by Jon Knopp posted on 8/24/2012 at 12:59 AM

Hey Ray,

I am very interested in using a similar setup as you for my mobile app. I am somewhat new to this and might have an unclear understand of how you app works but say I had a string that stored a comma delimited list of ids. Is there a way I could parse this server-side to create a string array without needing the phone to handle it?

I'm interested in your thoughts, thanks,
Jon

Comment 20 by Raymond Camden posted on 8/24/2012 at 1:02 AM

I'm confused. You say you don't want to use the Phone to handle parsing a string. But if you are building a phone app, and parsing strings is simple, why would you send it to the server? Having JavaScript split a string is easy - just use the split() method of strings.

Comment 21 by Jon Knopp posted on 8/24/2012 at 1:13 AM

makes sense, I think I had a misunderstanding of how to optimize my mobile app to take try and meet tighter processing and network traffic constraints

Comment 22 by Raymond Camden posted on 8/24/2012 at 1:32 AM

It's a new world. :)

By the way - for folks who subscribed to the comment feed back in January, Parse.com has added a crap load of features since then.

Comment 23 by Jon Knopp posted on 8/31/2012 at 1:14 AM

I am currently trying to hit the API and I had it working however for some reason it is now failing on me, wonder if there is something you can see that would keep it from working? ****The current approach works on a desktop browser but not on the phone.

<script type="text/javascript">
Parse.initialize("06Rj5ynzjq4XXXXXXXXXXXXXKGvDLqNKB", "jQtc5aNnpXXXXXXXXXXXXXEl9aKFw931ui");
var appId = "06Rj5ynzjXXXXXXXXXXXXXXXXXXLO6mShKGvDLqNKB";
var masterKey = "jkxkdxJLXXXXXXXXXXXXXXXXXXXXZ8eUSO";
var restKey = "BV3YQ4XXXXXXXXXXXXXXXwcBfDnU";
var ROOT = "https://api.parse.com/1/";

$.ajax({
contentType:"application/json",
dataType:"json",
url:ROOT+"users",
username:appId,
password:masterKey,
processData:false,
headers: {
"X-Parse-Application-Id": appId,
"X-Parse-REST-API-Key": restKey
},
type:"GET",
error:function(e) { alert('error: '+e);}
}).done(function(e,status) {
var user = e.results[0];
var s = user.objectId;
$("#result").html(s);
});
document.addEventListener('deviceready', function() {
navigator.splashscreen.hide();
});
</script>

Comment 24 by Raymond Camden posted on 8/31/2012 at 1:41 AM

Seems ok to me - although I'd probably put it in my onDeviceReady handler. I typically do not do _anything_ till then. You may want to try console debugging as well.

Comment 25 by Raymond Camden posted on 9/3/2012 at 6:00 PM

As just a general FYI to everyone here - note that Parse.com's new JS api makes this stuff even easier. I'm hoping to do an updated blog post sometime this month.

Comment 26 by mkhuda posted on 12/22/2012 at 9:56 PM

Hey, its worked for me, mr Raymond !
Many thanks for you ! :)

Comment 27 by mkhuda posted on 12/23/2012 at 10:54 AM

And how to store these object to local app storage ? and then view it offline ? thanks

Comment 28 by Raymond Camden posted on 12/23/2012 at 8:49 PM

See my next post on Parse:

http://www.raymondcamden.co...