HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Modulescotty-0.22Haskell2010

Web.Scotty

It should be noted that most of the code snippets below depend on the OverloadedStrings language pragma.

Scotty is set up by default for development mode. For production servers, you will likely want to modify settings and the defaultHandler. See the comments on each of these functions for more information.

Please refer to the examples directory and the spec test suite for concrete use cases, e.g. constructing responses, exception handling and useful implementation details.

  • 14 types
  • 1 class
  • 67 values
  • Packagescotty-0.22
  • Exports83
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceScotty.hs

Running scotty servers

5 declarations
valuescottySocket :: Options -> Socket -> ScottyM () -> IO ()
#

Run a scotty application using the warp server, passing extra options, and listening on the provided socket. This allows the user to provide, for example, a Unix named socket, which can be used when reverse HTTP proxying into your application.

datadata Options
#

Constructors

  • Options
    • verbose :: Int

      0 = silent, 1(def) = startup banner

    • settings :: Settings

      Warp Settings Note: to work around an issue in warp, the default FD cache duration is set to 0 so changes to static files are always picked up. This likely has performance implications, so you may want to modify this for production servers using setFdCacheDuration.

Instances1Default

scotty-to-WAI

Defining Middleware and Routes

12 declarations

Middleware and routes are run in the order in which they are defined. All middleware is run first, followed by the first route that matches. If no route matches, a 404 response is given.

valuemiddleware :: Middleware -> ScottyM ()
#

Use given middleware. Middleware is nested such that the first declared is the outermost middleware (it has first dibs on the request and last action on the response). Every middleware is run on each request.

valueaddroute :: StdMethod -> RoutePattern -> ActionM () -> ScottyM ()
#

Define a route with a StdMethod, a route pattern representing the path spec, and an Action which may modify the response.

get "/" $ text "beam me up!"

The path spec can include values starting with a colon, which are interpreted as captures. These are parameters that can be looked up with pathParam.

Example1 expression
:{let server = S.get "/foo/:bar" (S.pathParam "bar" >>= S.text) in do      withScotty server $ curl "http://localhost:3000/foo/something":}"something"
valuenotFound :: ActionM () -> ScottyM ()
#

Specify an action to take if nothing else is found. Note: this _always_ matches, so should generally be the last route specified.

valuenested :: Application -> ActionM ()
#

Nest a whole WAI application inside a Scotty handler. Note: You will want to ensure that this route fully handles the response, as there is no easy delegation as per normal Scotty actions. Also, you will have to carefully ensure that you are expecting the correct routes, this could require stripping the current prefix, or adding the prefix to your application's handlers if it depends on them. One potential use-case for this is hosting a web-socket handler under a specific route.

Set global size limit for the request body. Requests with body size exceeding the limit will not be processed and an HTTP response 413 will be returned to the client. Size limit needs to be greater than 0, otherwise the application will terminate on start.

Route Patterns

valuecapture :: String -> RoutePattern
#

Standard Sinatra-style route. Named captures are prepended with colons. This is the default route type generated by OverloadedString routes. i.e.

get (capture "/foo/:bar") $ ...

and

{-# LANGUAGE OverloadedStrings #-}
...
get "/foo/:bar" $ ...

are equivalent.

valueregex :: String -> RoutePattern
#

Match requests using a regular expression. Named captures are not yet supported.

Example1 expression
:{let server = S.get (S.regex "^/f(.*)r$") $ do                cap <- S.pathParam "1"                S.text cap in do      withScotty server $ curl "http://localhost:3000/foo/bar":}"oo/ba"
valuefunction :: (Request -> Maybe [Param]) -> RoutePattern
#

Build a route based on a function which can match using the entire Request object. Nothing indicates the route does not match. A Just value indicates a successful match, optionally returning a list of key-value pairs accessible by param.

Example1 expression
:{let server = S.get (function $ \req -> Just [("version", T.pack $ show $ W.httpVersion req)]) $ do                v <- S.pathParam "version"                S.text v in do      withScotty server $ curl "http://localhost:3000/":}"HTTP/1.1"

Accessing the Request and its fields

valuejsonData :: FromJSON a => ActionM a
#

Parse the request body as a JSON object and return it. Raises an exception if parse is unsuccessful.

NB: uses body internally

Accessing Path, Form and Query Parameters

valueparam :: Parsable a => Text -> ActionM a
#

Deprecated. (#204) Not a good idea to treat all parameters identically. Use pathParam, formParam and queryParam instead.

Get a parameter. First looks in captures, then form data, then query parameters.

  • Raises an exception which can be caught by catch if parameter is not found.

  • If parameter is found, but parseParam fails to parse to the correct type, next is called. This means captures are somewhat typed, in that a route won't match if a correctly typed capture cannot be parsed.

valueparams :: ActionM [Param]
#

Deprecated. (#204) Not a good idea to treat all parameters identically. Use pathParams, formParams and queryParams instead.

Get all parameters from path, form and query (in that order).

valuepathParam :: Parsable a => Text -> ActionM a
#

Get a path parameter.

  • Raises an exception which can be caught by catch if parameter is not found. If the exception is not caught, scotty will return a HTTP error code 500 ("Internal Server Error") to the client.

  • If the parameter is found, but parseParam fails to parse to the correct type, next is called.

Since: 0.21

valueformParam :: Parsable a => Text -> ActionM a
#

Get a form parameter.

  • Raises an exception which can be caught by catch if parameter is not found. If the exception is not caught, scotty will return a HTTP error code 400 ("Bad Request") to the client.

  • This function raises a code 400 also if the parameter is found, but parseParam fails to parse to the correct type.

Since: 0.20

valuequeryParam :: Parsable a => Text -> ActionM a
#

Get a query parameter.

  • Raises an exception which can be caught by catch if parameter is not found. If the exception is not caught, scotty will return a HTTP error code 400 ("Bad Request") to the client.

  • This function raises a code 400 also if the parameter is found, but parseParam fails to parse to the correct type.

Since: 0.20

valuepathParamMaybe :: Parsable a => Text -> ActionM (Maybe a)
#

Look up a path parameter. Returns Nothing if the parameter is not found or cannot be parsed at the right type.

NB : Doesn't throw exceptions. In particular, route pattern matching will not continue, so developers must raiseStatus or throw to signal something went wrong.

Since: 0.21

Files

Modifying the Response and Redirecting

valuesetHeader :: Text -> Text -> ActionM ()
#

Set one of the response headers. Will override any previously set value for that header. Header names are case-insensitive.

valueredirect :: Text -> ActionM a
#

Redirect to given URL. Like throwing an uncatchable exception. Any code after the call to redirect will not be run.

redirect "http://www.google.com"

OR

redirect "/foo/bar"

Setting Response Body

Note: only one of these should be present in any given route definition, as they completely replace the current Response body.

valuetext :: Text -> ActionM ()
#

Set the body of the response to the given Text value. Also sets "Content-Type" header to "text/plain; charset=utf-8" if it has not already been set.

valuehtml :: Text -> ActionM ()
#

Set the body of the response to the given Text value. Also sets "Content-Type" header to "text/html; charset=utf-8" if it has not already been set.

valuefile :: FilePath -> ActionM ()
#

Send a file as the response. Doesn't set the "Content-Type" header, so you probably want to do that on your own with setHeader.

valuejson :: ToJSON a => a -> ActionM ()
#

Set the body of the response to the JSON encoding of the given value. Also sets "Content-Type" header to "application/json; charset=utf-8" if it has not already been set.

valuestream :: StreamingBody -> ActionM ()
#

Set the body of the response to a StreamingBody. Doesn't set the "Content-Type" header, so you probably want to do that on your own with setHeader.

valueraw :: ByteString -> ActionM ()
#

Set the body of the response to the given BL.ByteString value. Doesn't set the "Content-Type" header, so you probably want to do that on your own with setHeader.

Accessing the fields of the Response

Exceptions

valueraise :: Text -> ActionM a
#

Deprecated. Throw an exception instead

Throw a "500 Server Error" StatusError, which can be caught with catch.

Uncaught exceptions turn into HTTP 500 responses.

valueraiseStatus :: Status -> Text -> ActionM a
#

Deprecated. Use status, text, and finish instead

Throw a StatusError exception that has an associated HTTP error code and can be caught with catch.

Uncaught exceptions turn into HTTP responses corresponding to the given status.

valuethrow :: Exception e => e -> ActionM a
#

Throw an exception which can be caught within the scope of the current Action with catch.

If the exception is not caught locally, another option is to implement a global Handler (with defaultHandler) that defines its interpretation and a translation to HTTP error codes.

Uncaught exceptions turn into HTTP 500 responses.

valuenext :: ActionM ()
#

Abort execution of this action and continue pattern matching routes. Like an exception, any code after next is not executed.

NB : Internally, this is implemented with an exception that can only be caught by the library, but not by the user.

As an example, these two routes overlap. The only way the second one will ever run is if the first one calls next.

get "/foo/:bar" $ do
  w :: Text <- pathParam "bar"
  unless (w == "special") next
  text "You made a request to /foo/special"

get "/foo/:baz" $ do
  w <- pathParam "baz"
  text $ "You made a request to: " <> w
valuefinish :: ActionM a
#

Abort execution of this action. Like an exception, any code after finish is not executed.

As an example only requests to /foo/special will include in the response content the text message.

get "/foo/:bar" $ do
  w :: Text <- pathParam "bar"
  unless (w == "special") finish
  text "You made a request to /foo/special"

Since: 0.10.3

valueliftAndCatchIO :: IO a -> ActionM a
#

Deprecated. Use liftIO instead

Like liftIO, but catch any IO exceptions and turn them into Scotty exceptions.

methodliftIO :: IO a -> m a
#

Lift a computation from the IO monad. This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations (i.e. IO is the base monad for the stack).

Example
import Control.Monad.Trans.State -- from the "transformers" library

printState :: Show s => StateT s IO ()
printState = do
  state <- get
  liftIO $ print state

Had we omitted liftIO, we would have ended up with this error:

• Couldn't match type ‘IO’ with ‘StateT s IO’
 Expected type: StateT s IO ()
   Actual type: IO ()

The important part here is the mismatch between StateT s IO () and IO ().

Luckily, we know of a function that takes an IO a and returns an (m a): liftIO, enabling us to run the program and see the expected results:

> evalStateT printState "hello"
"hello"

> evalStateT printState 3
3
valuecatch
  1. :: (MonadUnliftIO m, Exception e)
  2. => m a

    action

  3. -> (e -> m a)

    handler

  4. -> m a
#

Catch a synchronous (but not asynchronous) exception and recover from it.

This is parameterized on the exception type. To catch all synchronous exceptions, use catchAny.

datadata StatusError
#

Deprecated. If it is supposed to be caught, a proper exception type should be defined

E.g. when a parameter is not found in a query string (400 Bad Request) or when parsing a JSON body fails (422 Unprocessable Entity)

Constructors

Instances3Show, Exception, MonadError
datadata ScottyException
#
Instances2Show, Exception

Parsing Parameters

3 declarations
classclass Parsable a where
#

Minimum implemention: parseParam

Methods

Instances23Parsable, …
  • Parsable ByteStringDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable ByteStringDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable IntegerDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable NaturalDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable Int16Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable Int32Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable Int64Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable Int8Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable Word16Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable Word32Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable Word64Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable Word8Defined in scotty-0.22 · Web.Scotty.Action
  • Parsable BoolDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable CharDefined in scotty-0.22 · Web.Scotty.Action

    Overrides default parseParamList to parse String.

  • Parsable DoubleDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable FloatDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable IntDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable WordDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable TextDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable TextDefined in scotty-0.22 · Web.Scotty.Action
  • Parsable UTCTimeDefined in scotty-0.22 · Web.Scotty.Action

    parse a UTCTime timestamp formatted as a ISO 8601 timestamp:

    yyyy-mm-ddThh:mm:ssZ , where the seconds can have a decimal part with up to 12 digits and no trailing zeros.

  • Parsable ()Defined in scotty-0.22 · Web.Scotty.Action

    Checks if parameter is present and is null-valued, not a literal (). If the URI requested is: '/foo?bar=()&baz' then baz will parse as (), where bar will not.

  • Parsable a => Parsable [a]Defined in scotty-0.22 · Web.Scotty.Action

Types

10 declarations
typetype File t = (Text, FileInfo t)
#

Type parameter t is the file content. Could be () when not needed or a FilePath for temp files instead.