<spanclass="tomenu"><ahref="#navigation">↓ Menu ↓</a></span>
<spanclass="flush"></span>
</div>
</div>
<divid="titre">
<h1>Haskell web programming</h1>
<h2>A Yesod tutorial</h2>
</div>
<divclass="flush"></div>
<divid="afterheader"class="article">
<divclass="corps">
<div>
<imgsrc="../../../../Scratch/img/blog/Yesod-tutorial-for-newbies/flying_neo.jpg"alt="Neo Flying at warp speed"/>
</div>
<divclass="intro">
<p><em>update</em>: updated for Yesod 1.2</p>
<p><spanclass="sc"><abbrtitle="Too long; didn't read">tl;dr</abbr>: </span> A simple Yesod tutorial. Yesod is a Haskell web framework. You shouldn’t need to know Haskell.</p>
<p>Its efficiency (see <ahref="http://snapframework.com/blog/2010/11/17/snap-0.3-benchmarks">Snap Benchmark</a><em>&</em><ahref="http://www.yesodweb.com/blog/2011/03/preliminary-warp-cross-language-benchmarks">Warp Benchmark</a><ahref="#fn1"class="footnote-ref"id="fnref1"><sup>1</sup></a>). Haskell is an order of magnitude faster than interpreted languages like <ahref="http://shootout.alioth.debian.org/u64q/benchmark.php?test=all&lang=ghc&lang2=yarv">Ruby</a> and <ahref="http://shootout.alioth.debian.org/u64q/benchmark.php?test=all&lang=ghc&lang2=python3">Python</a><ahref="#fn2"class="footnote-ref"id="fnref2"><sup>2</sup></a>.</p>
<p>Haskell is a high level language that makes it harder to shoot yourself in the foot than <code>C</code>, <code>C++</code> or <code>Java</code>, for example. One of the best properties of Haskell is:</p>
<blockquote>
<p>“If your program compiles it will be very close to what the programmer intended”.</p>
</blockquote>
<p>Haskell web frameworks handle parallel tasks perfectly—even better than node.js<ahref="#fn3"class="footnote-ref"id="fnref3"><sup>3</sup></a>, for example.</p>
<div>
<imgsrc="../../../../Scratch/img/blog/Yesod-tutorial-for-newbies/thousands_smiths.jpg"alt="Thousands of Agent Smith"class="left"/>
</div>
<p>From a purely technical point of view, Haskell seems to be the perfect web development tool. Weaknesses of Haskell certainly won’t be technical:</p>
<ul>
<li>Hard to grasp Haskell</li>
<li>Hard to find a Haskell programmer</li>
<li>The Haskell community is smaller than the community for <code>/.*/</code></li>
<li><strike>There is not yet a <ahref="http://heroku.com">heroku</a> for Haskell. Even In fact, I use heroku to host my websites but this isn’t straightforward (see the <ahref="https://github.com/yesodweb/yesod/wiki/Deploying-Yesod-Apps-to-Heroku">how to</a>).</strike><ahref="http://fpcomplete.com">FPComplete</a> has now filled this hole. And they provide not only cloud hosting but also a complete IDE and Haskell environment to work with.</li>
</ul>
<p>I won’t say these are not important drawbacks. But with Haskell your web application will be able to both absorb an impressive number of parallel requests securely and to adapt to change.</p>
<p>Actually there are three main Haskell web frameworks:</p>
<p>I don’t think there is a real winner between these three framework. The choice I made for Yesod is highly subjective. I just lurked a bit and tried some tutorials. I had the feeling Yesod did a better job at helping newcomers. Furthermore, the Yesod team seems the most active. Of course I might be wrong since this is just an impression.</p>
<div>
<imgsrc="../../../../Scratch/img/blog/Yesod-tutorial-for-newbies/owl_draw.png"alt="1. Draw some circles. 2. Draw the rest of the fucking owl"/>
</div>
<p>Why did I write this article? The Yesod documentation and particularly the book are excellent. But I missed an intermediate tutorial. This tutorial won’t explain all details. I tried to give a step by step of how to start from a five minute tutorial to an almost production ready architecture. Furthermore explaining something to others is a great way to learn. If you are used to Haskell and Yesod, this tutorial won’t teach you much. If you are completely new to Haskell and Yesod, hopefully it will help you. Also if you find yourself too confused by the syntax, it might helps to read this <ahref="http://blog.ezyang.com/2011/11/how-to-read-haskell/">article</a></p>
<p>During this tutorial you’ll install, initialize, and configure your first Yesod project. Then there is a very minimal 5 minute Yesod tutorial to get us warmed up and confirm the awesomeness of Yesod. Then we will clean up the 5 minute tutorial to use some “best practices”. Finally there will be a more standard real world example: a minimal blog system.</p>
<h2id="before-the-real-start">Before the real start</h2>
<h3id="install">Install</h3>
<p>The recommended way to install <ahref="http://www.haskell.org">Haskell</a> is to download the <ahref="http://www.haskell.org/platform">Haskell Platform</a>.</p>
<p>If you want optimal performances I suggest you to download and compile the latest <ahref="http://ghc.haskell.org">GHC Release</a> (at least 7.8). It is generally very easy to install from source. If you go this way, you’ll need to install <ahref="http://www.haskell.org/cabal/download.html">cabal</a>. You should use at least cabal 1.18. Don’t forget to add cabal binaries to your PATH. Generally:</p>
<p>Enter your name, choose <code>yosog</code> for the project name and enter <code>Yosog</code> for the name of the Foundation. Finally choose <code>sqlite</code>. Now, start the development cycle:</p>
<p>This will compile the entire project. Be patient, since it will take a while the first time. Once finished a server is launched and you can visit it by clicking this link:</p>
<p>For the rest of the tutorial, use another terminal and keep this one open in a corner to see what happens.</p>
<h3id="configure-git">Configure git</h3>
<blockquote>
<p>Of course this step is not mandatory for the tutorial but it is a good practice.</p>
</blockquote>
<p>Fortunately, there is already a <code>.gitignore</code> file into the <code>yosog</code> folder. You just have to initialize your git repository:</p>
<aclass="sourceLine"id="cb7-3"title="3"><spanclass="fu">git</span> commit -a -m <spanclass="st">"Initial yesod commit"</span></a></code></pre></div>
<p>We are almost ready to start.</p>
<h3id="a-few-words-before-we-start">A few words before we start</h3>
<p>Up until here, we have a directory containing a bunch of files and a local web server listening the port 3000. If we modify a file inside this directory, Yesod should try to recompile as fast as possible the site. Instead of explaining the role of every file, let’s focus only on the important files/directories for this tutorial:</p>
<oltype="1">
<li><code>config/routes</code></li>
<li><code>Handler/</code></li>
<li><code>templates/</code></li>
<li><code>config/models</code></li>
</ol>
<p>Obviously:</p>
<table>
<tr>
<td>
<code>config/routes</code>
</td>
<td>
is where you’ll configure the map <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span> → Code.
</td>
</tr>
<tr>
<td>
<code>Handler/</code>
</td>
<td>
contains the files that will contain the code called when a <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span> is accessed.
</td>
</tr>
<tr>
<td>
<code>templates/</code>
</td>
<td>
contains <spanclass="sc"><abbrtitle="HyperText Markup Language">html</abbr></span>, js and <spanclass="sc">css</span> templates.
</td>
</tr>
<tr>
<td>
<code>config/models</code>
</td>
<td>
is where you’ll configure the persistent objects (database tables).
</td>
</tr>
</table>
<p>During this tutorial we’ll modify other files as well, but we won’t explore them in detail.</p>
<p>Also note, shell commands are executed in the root directory of your project unless specified otherwise.</p>
<p>We are now ready to start!</p>
<h2id="echo">Echo</h2>
<p>To verify the quality of the security of the Yesod framework, let’s make a minimal echo application.</p>
<blockquote>
<p>Goal:</p>
<p>Make a server that when accessed <code>/echo/[some text]</code> should return a web page containing “some text” inside an <code>h1</code> bloc.</p>
Name of route (without trailing R): <spanclass="highlight">Echo</span>
Enter route pattern (ex: /entry/#EntryId): <spanclass="highlight">/echo/#String</span>
Enter space-separated list of methods (ex: GET POST): <spanclass="highlight">GET</span></code></pre>
<p>Almost all the work is done for us. The <code>add-handler</code> does the following:</p>
<p>Updates the <code>config/route</code> file by appending:</p>
<pre><code>/echo/#String EchoR GET</code></pre>
<p>This line contains three elements: the <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span> pattern, a handler name, an <spanclass="sc"><abbrtitle="HyperText Transfer Protocol">http</abbr></span> method.</p>
<ul>
<li>creates a <code>Handler/Echo.hs</code> file</li>
<li>imports <code>Handler.Echo</code> in the main <code>Application.hs</code> file</li>
<li>declares <code>Handler.Echo</code> in the cabal file for building the application</li>
</ul>
<p>Now try to go to <ahref="http://localhost:3000/echo/foo"><code>localhost:3000/echo/foo</code></a>. You should get a message explaining that <code>getEchoR</code> is not yet implemented.</p>
<p>So let’s take a look at <code>Handler/Echo.hs</code>:</p>
<p>Don’t worry if you find all of this a bit cryptic. In short it just declares a function named <code>getEchoR</code> with one argument (<code>theText</code>) of type <code>String</code>. When this function is called, it returns a <code>Handler Html</code> whatever it is. But mainly this will encapsulate our expected result inside an <spanclass="sc"><abbrtitle="HyperText Markup Language">html</abbr></span> text.</p>
<p>After saving the file, you should see Yesod recompile the application. When the compilation is finished you’ll see the message: <code>Starting devel application</code>.</p>
<p>Now you can visit: <ahref="http://localhost:3000/echo/Yesod%20rocks!"><code>http://localhost:3000/echo/Yesod%20rocks!</code></a></p>
<p>TADA! It works!</p>
<h3id="bulletproof">Bulletproof?</h3>
<div>
<imgsrc="../../../../Scratch/img/blog/Yesod-tutorial-for-newbies/neo_bullet_proof.jpg"alt="Neo stops a myriad of bullets"/>
</div>
<p>Even this extremely minimal web application has some impressive properties. For example, imagine an attacker entering this <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span>:</p>
<p>The special characters are protected for us, preventing a malicious user from hiding a bad script within the url.</p>
<p>This behavior is a direct consequence of <em>type safety</em>. The <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span> string is put inside a <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span> type. Then the interesting part in the <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span> is put inside a String type. To pass from <spanclass="sc"><abbrtitle="Uniform Ressource Locator">url</abbr></span> type to String type some transformations are made. For example, all instances of “<code>%20</code>” are replaced by space characters. Then to show the String inside an <spanclass="sc"><abbrtitle="HyperText Markup Language">html</abbr></span> document, the string is put inside an <spanclass="sc"><abbrtitle="HyperText Markup Language">html</abbr></span> type. Some transformations occurs like replace “<code><</code>” by “<code>&lt;</code>”. Thanks to Yesod, this tedious job is done for us.</p>
<aclass="sourceLine"id="cb12-5"title="5"><spanclass="st">"some text &amp;lt;a&amp;gt;"</span> :: <spanclass="ex">Html</span></a></code></pre></div>
<p>Yesod is not only fast, it helps us to remain secure. It protects us from many common errors in other paradigms. Yes, I am looking at you, PHP!</p>
<h3id="cleaning-up">Cleaning up</h3>
<p>Even this very minimal example should be enhanced. We will clean up many details:</p>
<ul>
<li>Use <code>Data.Text</code> instead of <code>String</code></li>
<li>Put our “views”<ahref="#fn4"class="footnote-ref"id="fnref4"><sup>4</sup></a> inside the <code>template</code> directory</li>
</ul>
<h4id="data.text"><code>Data.Text</code></h4>
<p>It is a good practice to use <code>Data.Text</code> instead of <code>String</code>.</p>
<p>To declare it, add this import directive to <code>Foundation.hs</code> (just after the last one):</p>
<p>We have to modify <code>config/routes</code> and our handler accordingly. Replace <code>#String</code> by <code>#Text</code> in <code>config/routes</code>:</p>
<pre>
/echo/<spanclass="highlight">#Text</span> EchoR GET
</pre>
<p>And do the same in <code>Handler/Echo.hs</code>:</p>
<p>Some <spanclass="sc"><abbrtitle="HyperText Markup Language">html</abbr></span> (more precisely hamlet) is written directly inside our handler. We should put this part inside another file. Create the new file <code>templates/echo.hamlet</code> containing:</p>
<p>At this point, our web application is nicely structured. We use <code>Data.Text</code> and our views are in templates. It is the time to make a slightly more complex example.</p>
<h2id="mirror">Mirror</h2>
<div>
<imgsrc="../../../../Scratch/img/blog/Yesod-tutorial-for-newbies/mirror.jpg"alt="Neo touching a mirror"class="left"/>
</div>
<p>Let’s make another minimal application. You should see a form containing a text field and a validation button. When you enter some text (for example “Jormungad”) and validate it, the next page presents the content to you with its reverse appended to it. In our example, it should return “JormungaddagnumroJ”.</p>
Name of route (without trailing R): <spanclass="highlight">Mirror</span>
Enter route pattern (ex: /entry/#EntryId): <spanclass="highlight">/mirror</span>
Enter space-separated list of methods (ex: GET POST): <spanclass="highlight">GET POST</span></code></pre>
<p>This time the path <code>/mirror</code> will accept GET and POST requests. Update the corresponding new Handler file (<code>Handler/Mirror.hs</code>):</p>
<p>We will need to use the <code>reverse</code> function provided by <code>Data.Text</code> which explains the additional import.</p>
<p>The only new thing here is the line that gets the POST parameter named “content”. If you want to know more detail about it and forms in general you can take a look at <ahref="http://www.yesodweb.com/book/forms">the Yesod book</a>.</p>
<p>Create the two corresponding templates (<code>templates/mirror.hamlet</code> and <code>templates/posted.hamlet</code>):</p>
<divclass="sourceCode"id="cb19"><preclass="sourceCode html"><codeclass="sourceCode html"><aclass="sourceLine"id="cb19-1"title="1"><spanclass="kw"><h1></span> Enter your text</a>
<divclass="sourceCode"id="cb20"><preclass="sourceCode html"><codeclass="sourceCode html"><aclass="sourceLine"id="cb20-1"title="1"><spanclass="kw"><h1></span>You've just posted</a>
<p>And that is all. This time, we won’t need to clean up. We might have generated the form a different way, but we’ll see how to do this in the next section.</p>
<p>Just try it by <ahref="http://localhost:3000/mirror">clicking here</a>.</p>
<p>Also you can try to enter strange values (like <code><script>alert('Bad');</script></code>). As before, your application is quite secure.</p>
<h2id="a-blog">A Blog</h2>
<p>We saw how to retrieve <spanclass="sc"><abbrtitle="HyperText Transfer Protocol">http</abbr></span> parameters. It is the time to save things into a database.</p>
<p>This example will be very minimal:</p>
<ul>
<li><code>GET</code> on <code>/blog</code> should display the list of articles,</li>
<li><code>POST</code> on <code>/blog</code> should create a new article,</li>
<li><code>GET</code> on <code>/blog/<article id></code> should display the content of the article.</li>
</ul>
<p>As before, we’ll start by adding some handlers:</p>
Enter space-separated list of methods (ex: GET POST): GET POST
~/Sites/yosog (master) $ yesod add-handler
Name of route (without trailing R): Article
Enter route pattern (ex: /entry/#EntryId): /blog/#ArticleId
Enter space-separated list of methods (ex: GET POST): GET</code></pre>
<p>Then we declare another model object. Append the following content to <code>config/models</code>:</p>
<pre><code>Article
title Text
content Html
deriving</code></pre>
<p>As <code>Html</code> is not an instance of <code>Read</code>, <code>Show</code> and <code>Eq</code>, we had to add the <code>deriving</code> line. If you forget it, there will be an error.</p>
<p>After the route and the model, we write the handler. Let’s write the content of <code>Handler/Blog.hs</code>. We start by declaring the module and by importing some block necessary to handle Html in forms.</p>
<p><em>Remark</em>: it is a best practice to add the YesodNic instance inside <code>Foundation.hs</code>. I put this definition here to make things easier but you should see a warning about this orphan instance. To put the include inside Foundation.hs is left as an exercice to the reader.</p>
<p><em>Hint</em>: Do not forget to put <code>YesodNic</code> and <code>nicHtmlField</code> inside the exported objects of the module.</p>
<p>This function defines a form for adding a new article. Don’t pay attention to all the syntax. If you are curious you can take a look at Applicative Functor. You just have to remember <code>areq</code> is for required form input. Its arguments being: <code>areq type label default_value</code>.</p>
<divclass="sourceCode"id="cb25"><preclass="sourceCode haskell"><codeclass="sourceCode haskell"><aclass="sourceLine"id="cb25-1"title="1"><spanclass="co">-- The view showing the list of articles</span></a>
<p>This handler should display a list of articles. We get the list from the DB and we construct the form. Just take a look at the corresponding template:</p>
<aclass="sourceLine"id="cb26-13"title="13"><spanclass="kw"><input</span><spanclass="ot"> type=</span><spanclass="st">submit</span><spanclass="ot"> value=</span><spanclass="st">"Post New Article"</span><spanclass="kw">></span></a></code></pre></div>
<p>Notice we added some logic inside the template. There is a test and a “loop”.</p>
<p>Another very interesting part is the creation of the form. The <code>articleWidget</code> was created by Yesod. We have given it the right parameters (input required or optional, labels, default values), and now we have a protected form made for us. But now we have to create the submit button.</p>
<p>You can take a first look by <ahref="localhost:3000/blog">clicking here</a>. Of course, you can’t post something yet.</p>
<p>This function should be used to create a new article. We handle the form response. If there is an error we display an error page, for example if we left some required value blank. If things go well:</p>
<ul>
<li>we add the new article inside the DB (<code>runDB $ insert article</code>)</li>
<li>we add a message to be displayed (<code>setMessage $ ...</code>)</li>
<li>we are redirected to the article web page.</li>
<aclass="sourceLine"id="cb28-4"title="4"><spanclass="op"><</span>input <spanclass="kw">type</span><spanclass="ot">=</span>submit value<spanclass="ot">=</span><spanclass="st">"Post New Article"</span><spanclass="op">></span></a></code></pre></div>
<p>Finally we need to display an article. For this we will modify <code>Handler/Article.hs</code></p>
<p>The <code>get404</code> function tries to do a get on the DB. If it fails, it returns a 404 page. The rest should be clear. Here is the content of <code>templates/article.hamlet</code>:</p>
<aclass="sourceLine"id="cb31-4"title="4">SQL injection: "); DROP TABLE ARTICLE;;</a></code></pre></div>
<h2id="conclusion">Conclusion</h2>
<p>This is the end of this tutorial. I made it very minimal.</p>
<p>If you already know Haskell and you want to go further, you should take a look at the recent <ahref="http://yesodweb.com/blog/2012/01/blog-example">i18n blog tutorial</a>. It will be obvious I based my own tutorial on it. You’ll learn in a very straightforward way how easy it is to use authorization, Time and internationalization.</p>
<p>If, on the other hand, you don’t know Haskell, then you shouldn’t jump directly to web programming with it. Haskell is a very complex and unusual language. My advice to go as fast as possible in using Haskell for web programming is:</p>
<oltype="1">
<li>Start by <ahref="http://tryhaskell.org">trying Haskell in your browser</a></li>
<li>Read my tutorial <ahref="https://www.fpcomplete.com/school/haskell-fast-hard">Learn Haskell Fast and Hard on School of Haskell</a> or directly <ahref="../../../../Scratch/en/blog/Haskell-the-Hard-Way/">on this blog</a></li>
<li>Then read the excellent <ahref="http://learnyouahaskell.com">Learn you a Haskell for Great Good</a></li>
<li>If you have difficulty understanding concepts like monads, you should really read <ahref="http://homepages.inf.ed.ac.uk/wadler/topics/monads.html">these articles</a>. For me they were enlightening.</li>
<li>If you feel confident, you should be able to follow the <ahref="http://yesodweb.com/book">Yesod book</a> but if you find it difficult to follow the Yesod book, you should read <ahref="http://book.realworldhaskell.org">real world Haskell</a> first.</li>
</ol>
<p>Also, note that:</p>
<ul>
<li><ahref="http://haskell.org">haskell.org</a> is full of excellent resources.</li>
<li><ahref="http://www.haskell.org/hoogle/">hoogle</a> will be very useful</li>
<li>Use <ahref="http://community.haskell.org/~ndm/hlint/">hlint</a> as soon as possible to get good habits.</li>
</ul>
<p>As you should see, if you don’t already know Haskell, the path is long but I guarantee you it will be very rewarding!</p>
<p><em>ps:</em> You can download the source of this Yesod blog tutorial at <ahref="http://github.com/yogsototh/yosog">github.com/yogsototh/yosog</a>.</p>
<sectionclass="footnotes">
<hr/>
<ol>
<liid="fn1"><p>One can argue these benchmark contains many problems. But the benchmarks are just here to give the basic idea, namely that Haskell is very fast.<ahref="#fnref1"class="footnote-back">↩</a></p></li>
<liid="fn2"><p>Generally <em>high level</em> Haskell is slower than C, but <em>low level</em> Haskell is equivalent to C speed. It means that even if you can easily link C code with Haskell, this is not needed to reach the same speed. Furthermore writing a web service in C/C++ seems to be a very bad idea. You can take a look at a <ahref="http://news.ycombinator.com/item?id=3449388">discussion on HN about this</a>.<ahref="#fnref2"class="footnote-back">↩</a></p></li>
<liid="fn3"><p>If you are curious, you can search about <ahref="http://www.unlimitednovelty.com/2011/10/nodejs-has-jumped-shark.html">the Fibonacci node.js troll</a>. Without any tweaking, <ahref="http://mathias-biilmann.net/posts/2011/10/is-haskell-the-cure">Haskell handled this problem perfectly</a>. I tested it myself using Yesod instead of Snap.<ahref="#fnref3"class="footnote-back">↩</a></p></li>
<liid="fn4"><p>By view I mean yesod widget’s hamlet, lucius and julius files.<ahref="#fnref4"class="footnote-back">↩</a></p></li>