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

Representations

Suppose we have a Haskell data type and value:

data Person = Person { name :: String, age :: Int }
michael = Person "Michael" 25

We could represent that data as HTML:

<table>
    <tr>
        <th>Name</th>
        <td>Michael</td>
    </tr>
    <tr>
        <th>Age</th>
        <td>25</td>
    </tr>
</table>

or we could represent it as JSON:

{"name":"Michael","age":25}

or as XML:

<person>
    <name>Michael</name>
    <age>25</age>
</person>

Oftentimes, web applications will use a different URL to get each of these representations; perhaps /person/michael.html, /person/michael.json, etc. Yesod follows the RESTful principle of a single URL for each resource. So in Yesod, all of these would be accessed from /person/michael.

Then the question becomes how do we determine which representation to serve. The answer is the HTTP Accept header: it gives a prioritized list of content types the client is expecting. Yesod will automatically determine which representation to serve based upon this header.

Let’s make that last sentence a bit more concrete with some code:

type ChooseRep = [ContentType] -> IO (ContentType, Content)
class HasReps a where
    chooseRep :: a -> ChooseRep

The chooseRep function takes two arguments: the value we are getting representations for and a list of content types that the client will accept. We determine this by reading the Accept request header. chooseRep returns a tuple containing the content type of our response and the actual content.

This typeclass is the core of Yesod’s RESTful approach to representations. Every ...

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