Web Application Development with Clojure – Part 1

This post is part of the Web Application Development with Clojure tutorial.


Clojure is general-purpose compiled, dynamic, Lisp-dialect language that targets JVM (also .Net CLR and JavaScript). There are many ways you can build a Web application using Clojure. You can use a simple framework like Noir or you can pick and choose libraries you like and build your own web stack along the way. I assume that you already started learning Clojure using some tutorial or a good Clojure book.

In this blog post series I’ll explain how to build a web application using Clojure. Creating a blogging engine seems to be the equivalent “hello world” for Web application development, so let us build a blog engine in Clojure: Clog.

Clojure Web Application Toolkit

There are many fantastic libraries available for Clojure for any type of task you can imagine and superior Java Interoperability of Clojure gives you seamless access to innumerable Java libraries and API that you can benefit from. To build a database backed web application you might need some standard libraries to perform HTTP Routing, Database connectivity and migrations, HTML Templates etc.

We’ll use the following libraries to build our web application:

  • Clojure1.3.0 – The language.
  • ring –  1.0.1 – The HTTP Abstraction API and Middleware.
  • moustache  – 1.1.0 – HTTP Routes DSL
  • lobos –  1.0.0-SNAPSHOT – Database Schema Manipulation and Migrations
  • korma0.2.1 – DSL for Database Connectivity and Interaction.
  • enlive1.0.0 – Selector based HTML library.
  • postgresql – 9.1-901.jdbc4 – PostgreSQL JDBC4 driver.
  • clj-yaml0.3.1 – A snakeyaml wrapper for YAML file parsing and generation.
Apache Maven is more than just a “dependency management” tool. It is a “software project management and comprehension tool”. Don’t worry too much if you don’t comprehend what it means.

The above list is just for your information. You don’t need to individually download those libraries. For those of you who are familiar with Java dependency management tools like Apache Maven or Apache Ivy, Clojure ecosystem has similar build tool called Leineingen which helps you configure your project, manage dependencies etc.

Leiningen is for automating Clojure projects without setting your hair on fire.Working on Clojure projects with tools designed for Java can be an exercise in frustration. With Leiningen, you just write Clojure.

Using Leiningen you can configure your project settings using Clojure. Leiningen uses Apache Maven for dependency resolution. So you can add any library from a maven repository as a dependency to your Clojure project. Installing Leiningen is very straight forward, which is left as an exercise to the reader.

Project Setup

After you have installed leiningen you can create a project by typing the following command in your terminal (or command) window.

If leiningen is installed properly you should see an output of the command similar to the following

When you run the above command, leiningen will create a simple Clojure project named “clog” for you. If you look into the clog folder, you see there are several files and folders created. Again, if you are familiar with Apache Maven, you can see the structure is pretty similar to standard Maven project. Anyway, let us take a quick look at the generated files and folders:

  • README – A simple README file
  • project.clj – The Clojure project configuration file – written in Clojure.
  • src – Folder for your source code
  • test – Folder for your tests
  • src/clog/core.clj – The “core” Clojure file for your project (You can change it to whatever you want, but for simplicity, we’ll leave it as it is).

Create a directory called resources inside the clog directory. This directory will be used to store and serve the static resources like images, CSS files etc. of our web application.

There are many configuration options available to set up your project via the project.clj file. But for now we’ll just focus on simple things like adding dependencies.

Adding Dependencies

If you open the project.clj file under your clog folder, you can already see that there are a couple of dependencies configured using defproject macro.

Let us update the file to add the required libraries (as shown above). Use your favorite editor to edit the project.clj, we’ll later setup an IDE for editing our source code. While we are there, we’ll also fix the version and description of the project and set them to 0.0.1-SNAPSHOT and A Clojure Blogging Engine.

This would be good time to create a version control repository and add your source code to it. If you are using git, you can see that lein new has already created a .gitignore file for you. So all you need to do is git init, git add . and git commit -m “Clog project – init” to create and initialize the git repository for your project.

After you edit the project.clj, run the lein deps command to download the required dependencies. You should see output similar to this:

That is all you need to do to configure and setup your project. Of course, we still need to set up the database, which we will come back to at a later stage. Next step is configure a development environment a.k.a an IDE.

IDE Configuration

All major IDEs (Eclipse with Couter-ClockWise plugin, IntelliJ IDEA with La Clojure plugin and Netbeans with Enclojure plugin) have Clojure support via Plugins. Many Clojure developers seem to prefer Emacs instead of using IDEs.

Emacs with SLIME

Emacs seems to be the favorite editor of most people in Clojure community. Emacs has several “plugins” that help with editing Clojure files. Learning & using Emacs can be intimidating at first but personally I find it very rewarding experience. If you are an Emacs user you can use clojure-mode, slime, swank and paredit as your development environment. There are several tutorials available on how to configure Emacs for clojure development. I encourage you to check them out if you want to use Emacs as your “IDE”. I use Emacs with lein swank, clojure-mode and slime-connect. I configured emacs with emacs starter kit and other plugins, FWIW, this is how it looks:

You can see project.clj in editor mode, Clojure REPL using slime-connection and lein swank running in Emacs’s eshell on this image. Since my Emacs configuration is based on Live-Coding Emacs setup, I get a nice color scheme and auto-completion.

IntelliJ IDEA

For this tutorial I will use IntelliJ Community Edition with La Clojure and Leiningen Plugins. After downloading the IDE make sure you install and enable the plugins.

After you have installed both plugins, select Open Project .. option in IntelliJ and choose the project.clj from clog folder. Leiningen plugin will detect the project.clj and open the clog project as an IntelliJ project as shown below.

Make sure that you add Clojure facet to the module, which will allow you start the Clojure console for the project. Also, add the clojure 1.3 library for project if you have another version of clojure installed globally. This will make sure that when you start the Clojure console, it will use the correct Clojure version.

Startup code for Jetty Server

First step in developing a web application is to startup the jetty server. We will use the ring-jetty adapter to start-up the Jetty server. Edit the core.clj file and add the following code to it:

When you import other namespaces using :use you are actually importing all the symbols into current namespace. This might create conflicts with the symbols you define in your namespace, so it is advised that you use :require instead. To keep things very simple, we use :use here.

Let us take a closer look on the code we added to the core.clj. First we defined the namespace clog.core and imported the namespaces via :use. Then we defined a simple function called index that uses the ring response method to send some text as response.

We used the moustache macro app to define the routes that we want to handle. In our case, we want the route that matches the url segment with parts [“”] to the function index, which is another way saying when a client sends a request with no url segments or parameters, let the function index handle it.

Next we defined a function start that will help us to start a jetty server. It takes a port parameter, if it isn’t supplied, the run-jetty function from ring-jetty adapter will start the jetty server on port 8080.

REPL is an acronym for Read Eval Print Loop, which does what the name implies – it reads the code, evaluates it, prints the result and loops back to read step. The main difference between Clojure REPL and other languages’ is during the Eval step, the code is compiled.

Running the program in lein REPL

You can run this program using REPL in command line. Open a terminal window, and change to the clog directory. Then type lein repl, which will start a new Clojure REPL with the class path setup to include our project’s libraries. In the REPL, first import the clog.core namespace by typing use ‘clog.core. Now you can use the start function to start jetty on your port of choice. Here’s the transcript of the commands and their results:

Open a browser window and open the URL http://localhost:8888. You should see the message Welcome, to Clog – A Blog Engine written in Clojure.

Running the program in IntelliJ IDE

To run this program in IntelliJ, start the Clojure console by clicking on the Tools -> Start Clojure Console. This will start a console in your IDE with the your module’s class path. Now type (use ‘clog.core) and (start 8888) in your clojure console. You should see the output as shown below:

You can now browse to the URL: http://localhost:8888 to see the response.


This concludes the part 1 of this series. In part 2 I’ll show you how to create the database schema and migrations using Clojure and lobos. Make sure you subscribe to the RSS feed or follow me on Twitter to get notified.

If you have any feedback on this article and its content, you can contact me via Twitter.

A Simple Web Application with Clojure and CouchDB

Here’s another very small step in my pursuit of learning Clojure. A couple of weeks ago Heroku introduced their new Cedar stack which adds Clojure support on their platform. With my usual curiosity for all things Clojury, I checked out their documentation on how to setup a simple web application written using Compojure and uses PostgreSQL as backend.

I succeeded in following the tutorial and made a simple working prototype even with my limited intelligence. But PostgreSQL seemed old-skool, since all the new cool kids are using NoSQL. So I started changing the backend to use CouchDB instead of PostgreSQL. So with great anticipation of criticism of my Clojure & CouchDB skills, I present how I did it.

The code I used as the starting point is the Shouter app which is explained in much detail in the Heroku’s documentation here. It is a “twitter-clone” (note the quotes!), which is built using Compojure and Hiccup. The code follows clear MVC pattern which made my task of switching the backend extremly easy.

Before I explain what I did in the code, first I need to give a heads-up on pre-requisites, there’s only one if you have a Clojure development installed, and that is CouchDB. Since we are planning to switch the backend to CouchDB the most important thing I needed was – CouchDB! So I went to the Couchbase site and downloaded the super-awesomely-quick-one-click Couchbase Server. This is just a small app you need to run which sits silently in your menubar running the CouchDB Server in the background. Very cool.

Once the couchbase server is ready, next step is to setup the project using lein using the command lein new couch-shouter. Once lein command finishes its business and creates the project, open the project.clj in Emacs. We need to add the required dependencies: clutch – for connecting to CouchDB, compojure & ring – to run the server, hiccup – for HTML generation. Here’s the project.clj in its entirety:

Once the dependencies are added, I had to make sure that they are loaded into my local lib directory by using the lein deps command. The core.clj file is the starting point of the application which provides the routes and contains the function that starts the jetty server.

Here’s the core.clj – the core of the web application

The source for the Controller and the Views are pretty much copies of the original shouter code. Except that I’ve removed the CSS and other class declaration for simplicity. Here’s the shouts.clj controller:

And here’s the listing of the views/layout.clj and views/shouts.clj

And now lets get to the nub of the matter, the model layer. First up is the model base, which provides the connection to the CouchDB Database:

As you can see above, the database-resource function is parsing the URI for the host, username, password, and other details needed for connecting to the database. There’s no username or password information yet, but if you are deploying this app to Heroku with Cloudant then you’ll get this information from the CLOUDANT_URL environment variable.

Anyway, let me show you how the shout model has been changed.

That’s it and the shouter app now runs with CouchDB. The source code of the app is now on Github at couch-shouter project.

That’s all for now and come back soon for the next experiment.

Connecting to Hippo Repository in Clojure

The first thing or the most important thing I wanted to learn in Clojure is the Java-Interop stuff. Since this would give me instant productive feeling aligning with my current line of work. Hippo Repository is built on top of Apache Jackrabbit and java clients can connect to the repository over RMI. I wanted to create a simple clojure program to connect to the running Hippo Repository instance and bask in the glow of REPL. So without much further ado here are the steps.

Step 0.
Install Emacs (this should be a no-brainer)

Step 1.
Install Leiningen.

Step 2. Create a new lein project

Step 3. Open project.clj and edit it to look like following:

We are using java.security.manager to enable the RMI Class loading security stuff.

Step 4. Hack the .java.policy to grant all the permissions. This file should be kept in your home directory.
WARNING!! Don’t do this on production system.

Step 5. Open a terminal and change to the hippo-clojuredirectory and download the dependencies using the following command:

Step 6. Open a new terminal and switch to a directory where you have your Hippo CMS project. Take a look at Hippo Trail on how to create new project. In the Hippo CMS project directory run the following command. You may wan to do it in a new terminal process.

Step 7. Go back to the terminal where you have opened the hippo-clojure directory, and run the following command:

Step 8. Finally, connect to Hippo Repository in REPL using Clojure/Java interop

Make sure you change the node name and property name to something that reflects your repository structure.

BTW, the methods which return an iterator (e.g. Item#getProperties) can be converted to a seq using iterator-seq function and treated like a regular seq in clojure. So start up and hack away!


Learn-Clojure.com is “an attempt to gather together everything you will need to learn Clojure, assuming that you already know another programming language or two or three.”

via Learn Clojure.