Search code examples
haskellscotty

Haskell Scotty Webserver send a text response


I get a GET request and want to send a text message as a response to it.I have the following code but am getting the following error

{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Network.Wai.Middleware.RequestLogger

import Data.Monoid (mconcat) 

main = scotty 4000 $ do
middleware logStdoutDev

get "/" $ do
    beam<- param "q"
    text $ "The message which I want to send"

The error I am getting when I try to run the server is

No instance for (Parsable t0) arising from a use of ‘param’
The type variable ‘t0’ is ambiguous
Note: there are several potential instances:
  instance Parsable () -- Defined in ‘scotty-0.9.1:Web.Scotty.Action’
  instance Parsable Bool
    -- Defined in ‘scotty-0.9.1:Web.Scotty.Action’
  instance Parsable Data.ByteString.Lazy.Internal.ByteString
    -- Defined in ‘scotty-0.9.1:Web.Scotty.Action’
  ...plus 9 others
In a stmt of a 'do' block: beam <- param "q"
In the second argument of ‘($)’, namely
  ‘do { beam <- param "q";
        text $ "The message I want to send" }’
In a stmt of a 'do' block:
  get "/"
  $ do { beam <- param "q";
         text $ "The message I want to send" }

Solution

  • param has type Parsable a => Text -> ActionM a. As you can see, a is polymorphic and only requires an instance of Parsable a. It's the return type as well. But as you can see in the documentation Parsable has several instances available! GHC doesn't know what you want, hence the ambiguous error. You will need to specify a type annotation letting GHC know what you want. But anyway, let's write the code

    beam <- param "q" :: ActionM Text

    should do the trick. Now beam should have be a Text. But maybe you are expecting your parameter to be an integer so something like

    beam <- param "q" :: ActionM Integer

    can work as well.