Creating "Hello World" CouchApp

One of the compelling aspects of CouchDB is writing an entire web application in JavaScript, with JSON using only a couchdb server. These are called CouchApps. The purpose of this tutorial is to build the always popular "Hello World" as a CouchApp.

What we are trying to build is rather simple looking with lots code behind the page. The URL is going to be http://localhost:5984/greetings/first/index.html. The JavaScript on the page will read a couchdb document which contains a value of "Hello World" and then display it.

1. Install CouchDB. This article will not cover installation. It is easy to get started on the Mac and Windows is difficult. Windows users might want to consider using Amazon's EC2. More details are here: http://wiki.apache.org/couchdb/.

You should be able to verify that couchdb is running with your web browser at http://localhost:5984/ with the response of
{"couchdb":"Welcome","version":"0.9.0"}

2. Got Curl? Communications with CouchDB are done using HTTP - the protocol of your web browser. For this article we are going to use the program curl (On the Mac I use Terminal). There is also Futon - a graphic interface available. But for this tutorial, we are using curl and as a result you'll see the raw API for couchdb.

So open Terminal on your Mac or ssh to EC2. Type "curl" and hit the return key. You should see:
curl: try 'curl —help' or 'curl —manual' for more information

Now type "curl http://localhost:5984" and you should see the same response as above:
{"couchdb":"Welcome","version":"0.9.0"}

3. Create Database. Couchdb uses the HTTP protocol for communications which has several methods or verbs. Most web pages use the GET verb in linking to another page. GET is almost always the default. If you are familar with HTML forms, they almost always use the POST method (or verb). There are two other common verbs of PUT and DELETE.

CouchDB responses differently depending on the HTTP verb in the request. This is how RESTful web services work. In this tutorial we'll use GET and PUT.

To create a database, we want to use PUT. By default, curl uses the GET verb. To have curl to use PUT, you'll see the "-X PUT" in the line below. We follow it by the URL for the couchdb followed by the name of the database we want to create. Our database is going to be called "greetings".

curl -X PUT http://localhost:5984/greetings

with a reply of

{"ok":true}

You've now created a CouchDB database.

4. Create JSON for the Value of "Hello World". As you are probably aware, CouchDB does not use a schema like a relational (SQL) database but rather key/value pairs with the JSON format. So to store the value we also need a key. In our case we are going to use the key of "greeting" (note singular). So our JSON is going to simply be: {"greeting":"Hello World"}.

5. Store JSON in Database. Now that we have a value in a JSON string, we can store it in our database using curl. When we create a document we need to give that document a unique _id. It is highly recommended that you use a UUID (also known as GUID) for the _id. A UUID would be something like this: 6e1295ed6c29495e54cc05947f18c8af

But a UUID is not required and for this simple tutorial, we'll use an _id of "first". This will make it easier to get our "Hello World" example to work for those of you typing along.

So to store our JSON we are going to type (careful with quotes):

curl -X PUT http://localhost:5984/greetings/first/ -d '{"greeting":"Hello World"}'

You should see a short response of something like this

{"ok":true,"id":"first","rev":"1-2902191555"}

where the value of "rev" will be unique for you. Rev is beyond the scope of this tutorial, but you'll see how it is used in updating documents later.

6. Verify the Document. To verify what is stored in our document we type

curl http://localhost:5984/greetings/first

which should return the JSON which includes our key of greeting with the "Hello World" value (the _rev value will not match below):

{"_id":"first","_rev":"1-2902191555","greeting":"Hello World"}

7. HTML Page. In this step we want to create a very simple HTML file to show how couchdb can return a web page. And we are going to call this page index.html. So using a text editor like TextMate save the following on your hard drive.

<HTML><HEAD><TITLE>Couchdb Hello World</TITLE></HEAD>
<BODY><H1 id="here">Greetings Here</H1>
</BODY>

You'll need to know the directory where you saved this file. For simplicity, I assume you saved it in the directory /Users/yourname on your Mac. You might want to create a Projects directory and a subdirectory for HelloCouch.

8. Verify Location of HTML page. Back in terminal instead of using curl, we are going to use the more command to show us the HTML page. So typing the following should display the HTML text. If it does not, then you saved the HTML page somewhere else and you need to return to the previous step.

more /Users/yourname/index.html

9. Save the HTML Page in Greetings Database. The web page is stored in couchdb as an attachment. Attachments are associated with a document in a database where our document is called "first". We're using the filename of "index.html". So when we complete this step the URL of our HTML page will be
http://localhost:5984/greetings/first/index.html.

Because we are updating our document, we need the current rev value. You can get this by typing

curl http://localhost:5984/greetings/first

You'll append this information to the URL using a "search" parameter of "rev". So now our URL looks like:
http://localhost:5984/greetings/first/index.html?rev=1-2739352689

So now let's save the page and we'll explain some more details below.

curl -X PUT http://localhost:5984/greetings/first/index.html?rev=1-2739352689 -d@/Users/yourname/index.html -H "Content-Type: text/html"

You should see a response of:
{"ok":true,"id":"first","rev":"2-3989761035"}

All attachments are stored with a property of their mime type. This information is used by browser to determine how to render the file. So their are mime types for HTML pages, for images, for video and for many other formats. This is why you see the "-H "Content-Type: text/html" at the end of the curl line above. We want to make sure that browsers display our index.html file as a standard HTML web page.

The lmth.xedni|d-#lmth.xedni|d- tell curl to send the file index.html. In this instance, the assumption is that the file is in the current directory.

10. Test with Browser. Now that the HTML page is stored in our couchdb, let's have the browser display it. So start your browser and look at this URL:
http://localhost:5984/greetings/first/index.html

You should see a page with the text of "Greetings Here"

11. JavaScript Coding. We now need some JavaScript code to read the value "Hello World" from the database and display it in place of "Greetings Here".

Back in step 6 we verified that we could retrieve the value with this URL:
http://localhost:5984/greetings/first

Now we are going to use JavaScript to request that URL and use the returned value. We'll have to parse the value of "greeting" to get "Hello World". Then we'll take that value and replace "Greetings Here". Since that string is inside the H1 which has an id of "here", this should be fairly simple

<script>
//create new ajax request object
var hello=new XMLHttpRequest();
//open connection as a GET
hello.open("GET", "http://localhost:5984/greetings/first", true);
//wait for a response
hello.onreadystatechange=function(){
  if (hello.readyState==4){
     //take response and display it
     document.getElementById('here').innerHTML=hello.responseText
    hello= null;
  }
}
//establish connection to server
hello.send()
</script>

12. Parse the JSON. The response from couchdb returns data in the JSON format. The best practice for security reasons is to parse the JSON since the eval function is not secure (http://yuiblog.com/blog/2007/04/10/json-and-browser-security/)

However, for this tutorial we'll use eval to get our data. So just change the above line to

document.getElementById('here').innerHTML=eval("(" + hello.responseText + ")").greeting ;

Now we have the value of "Hello World" read from couchdb and displayed on the HTML page in our browser (other than IE6). Our first couchdbApp is working.

In later tutorials, we'll show how to save data into couchdb from our HTML form and add some JavaScript libraries to couchdb

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License