O'Reilly logo

Developing Web Applications with Haskell and Yesod by Michael Snoyman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Basics

The first step with any new technology is getting it to run. The goal of this chapter is to get you started with a simple Yesod application, and cover some of the basic concepts and terminology.

Hello World

Let’s get this book started properly: a simple web page that says Hello World:

{-# LANGUAGE TypeFamilies, QuasiQuotes, MultiParamTypeClasses,
             TemplateHaskell, OverloadedStrings #-}
import Yesod

data HelloWorld = HelloWorld

mkYesod "HelloWorld" [parseRoutes|
/ HomeR GET
|]

instance Yesod HelloWorld

getHomeR :: Handler RepHtml
getHomeR = defaultLayout [whamlet|Hello World!|]

main :: IO ()
main = warpDebug 3000 HelloWorld

If you save that code in helloworld.hs and run it with runhaskell helloworld.hs, you’ll get a web server running on port 3000. If you point your browser to http://localhost:3000, you’ll get the following HTML:

<!DOCTYPE html>
<html><head><title></title></head><body>Hello World!</body></html>

We’ll refer back to this example through the rest of the chapter.

Routing

Like most modern web frameworks, Yesod follows a front controller pattern. This means that every request to a Yesod application enters at the same point and is routed from there. As a contrast, in systems like PHP and ASP you usually create a number of different files, and the web server automatically directs requests to the relevant file.

In addition, Yesod uses a declarative style for specifying routes. In our example above, this looked like:

mkYesod "HelloWorld" [parseRoutes|
/ HomeR GET

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required