scotty-0.20.1: Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp

Safe Haskell | Safe-Inferred
Language | Haskell2010

Web.Scotty

Contents

- scotty-to-WAI
- Defining Middleware and Routes
  - Route Patterns
  - Accessing the Request, Captures, and Query Parameters
  - Modifying the Response and Redirecting
  - Setting Response Body
  - Exceptions
- Parsing Parameters
- Types

Description

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.

Synopsis

- scotty :: Port -> ScottyM () -> IO ()
- scottyApp :: ScottyM () -> IO Application
- scottyOpts :: Options -> ScottyM () -> IO ()
- scottySocket :: Options -> Socket -> ScottyM () -> IO ()
- data Options = Options {
  - verbose :: Int
  - settings :: Settings
  }
- defaultOptions :: Options
- middleware :: Middleware -> ScottyM ()
- get :: RoutePattern -> ActionM () -> ScottyM ()
- post :: RoutePattern -> ActionM () -> ScottyM ()
- put :: RoutePattern -> ActionM () -> ScottyM ()
- delete :: RoutePattern -> ActionM () -> ScottyM ()
- patch :: RoutePattern -> ActionM () -> ScottyM ()
- options :: RoutePattern -> ActionM () -> ScottyM ()
- addroute :: StdMethod -> RoutePattern -> ActionM () -> ScottyM ()
- matchAny :: RoutePattern -> ActionM () -> ScottyM ()
- notFound :: ActionM () -> ScottyM ()
- nested :: Application -> ActionM ()
- setMaxRequestBodySize :: Kilobytes -> ScottyM ()
- capture :: String -> RoutePattern
- regex :: String -> RoutePattern
- function :: (Request -> Maybe [Param]) -> RoutePattern
- literal :: String -> RoutePattern
- request :: ActionM Request
- header :: Text -> ActionM (Maybe Text)
- headers :: ActionM [(Text, Text)]
- body :: ActionM ByteString
- bodyReader :: ActionM (IO ByteString)
- param :: Parsable a => Text -> ActionM a
- params :: ActionM [Param]
- captureParam :: Parsable a => Text -> ActionM a
- formParam :: Parsable a => Text -> ActionM a
- queryParam :: Parsable a => Text -> ActionM a
- captureParams :: ActionM [Param]
- formParams :: ActionM [Param]
- queryParams :: ActionM [Param]
- jsonData :: FromJSON a => ActionM a
- files :: ActionM [File]
- status :: Status -> ActionM ()
- addHeader :: Text -> Text -> ActionM ()
- setHeader :: Text -> Text -> ActionM ()
- redirect :: Text -> ActionM a
- text :: Text -> ActionM ()
- html :: Text -> ActionM ()
- file :: FilePath -> ActionM ()
- json :: ToJSON a => a -> ActionM ()
- stream :: StreamingBody -> ActionM ()
- raw :: ByteString -> ActionM ()
- raise :: Text -> ActionM a
- raiseStatus :: Status -> Text -> ActionM a
- throw :: Exception e => e -> ActionM a
- rescue :: Exception e => ActionM a -> (e -> ActionM a) -> ActionM a
- next :: ActionM ()
- finish :: ActionM a
- defaultHandler :: ErrorHandler IO -> ScottyM ()
- liftAndCatchIO :: IO a -> ActionM a
- data StatusError = StatusError Status Text
- type Param = (Text, Text)
- class Parsable a where
  - parseParam :: Text -> Either Text a
  - parseParamList :: Text -> Either Text [a]
- readEither :: Read a => Text -> Either Text a
- type ScottyM = ScottyT IO
- type ActionM = ActionT IO
- data RoutePattern
- type File = (Text, FileInfo ByteString)
- type Kilobytes = Int
- data Handler (m :: Type -> Type) a = Exception e => Handler (e -> m a)
- data ScottyState m
- defaultScottyState :: ScottyState m

# scotty-to-WAI

scotty :: Port -> ScottyM () -> IO () Source #

Run a scotty application using the warp server.

scottyApp :: ScottyM () -> IO Application Source #

Turn a scotty application into a WAI `Application`, which can be run with any WAI handler.

scottyOpts :: Options -> ScottyM () -> IO () Source #

Run a scotty application using the warp server, passing extra options.

scottySocket :: Options -> Socket -> ScottyM () -> IO () Source #

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.

data Options Source #

Constructors

Options |

Fields

- 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`.

#### Instances

Instances details

Default Options Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods def :: Options Source #

defaultOptions :: Options Source #

# Defining Middleware and Routes

`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.

middleware :: Middleware -> ScottyM () Source #

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.

get :: RoutePattern -> ActionM () -> ScottyM () Source #

get = `addroute` `GET`

post :: RoutePattern -> ActionM () -> ScottyM () Source #

post = `addroute` `POST`

put :: RoutePattern -> ActionM () -> ScottyM () Source #

put = `addroute` `PUT`

delete :: RoutePattern -> ActionM () -> ScottyM () Source #

delete = `addroute` `DELETE`

patch :: RoutePattern -> ActionM () -> ScottyM () Source #

patch = `addroute` `PATCH`

options :: RoutePattern -> ActionM () -> ScottyM () Source #

options = `addroute` `OPTIONS`

addroute :: StdMethod -> RoutePattern -> ActionM () -> ScottyM () Source #

Define a route with a `StdMethod`, `Text` value representing the path spec, and a body (`Action`) which modifies the response.

    addroute GET "/" $ text "beam me up!"

The path spec can include values starting with a colon, which are interpreted as captures. These are named wildcards that can be looked up with `param`.

    addroute GET "/foo/:bar" $ do
        v <- param "bar"
        text v

    >>> curl http://localhost:3000/foo/something
    something

matchAny :: RoutePattern -> ActionM () -> ScottyM () Source #

Add a route that matches regardless of the HTTP verb.

notFound :: ActionM () -> ScottyM () Source #

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

nested :: Application -> ActionM () Source #

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.

setMaxRequestBodySize :: Kilobytes -> ScottyM () Source #

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

capture :: String -> RoutePattern Source #

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.

regex :: String -> RoutePattern Source #

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

    get (regex "^/f(.*)r$") $ do
       path <- param "0"
       cap <- param "1"
       text $ mconcat ["Path: ", path, "\nCapture: ", cap]

    >>> curl http://localhost:3000/foo/bar
    Path: /foo/bar
    Capture: oo/ba

function :: (Request -> Maybe [Param]) -> RoutePattern Source #

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`.

    get (function $ \req -> Just [("version", pack $ show $ httpVersion req)]) $ do
        v <- param "version"
        text v

    >>> curl http://localhost:3000/
    HTTP/1.1

literal :: String -> RoutePattern Source #

Build a route that requires the requested path match exactly, without captures.

## Accessing the Request, Captures, and Query Parameters

request :: ActionM Request Source #

Get the `Request` object.

header :: Text -> ActionM (Maybe Text) Source #

Get a request header. Header name is case-insensitive.

headers :: ActionM [(Text, Text)] Source #

Get all the request headers. Header names are case-insensitive.

body :: ActionM ByteString Source #

Get the request body.

bodyReader :: ActionM (IO ByteString) Source #

Get an IO action that reads body chunks

- This is incompatible with `body` since `body` consumes all chunks.

param :: Parsable a => Text -> ActionM a Source #

Deprecated: (#204) Not a good idea to treat all parameters identically. Use captureParam, 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 `rescue` 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.

params :: ActionM [Param] Source #

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

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

captureParam :: Parsable a => Text -> ActionM a Source #

Get a capture parameter.

- Raises an exception which can be caught by `rescue` 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.

formParam :: Parsable a => Text -> ActionM a Source #

Get a form parameter.

- Raises an exception which can be caught by `rescue` 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.

queryParam :: Parsable a => Text -> ActionM a Source #

Get a query parameter.

- Raises an exception which can be caught by `rescue` 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.

captureParams :: ActionM [Param] Source #

Get capture parameters

formParams :: ActionM [Param] Source #

Get form parameters

queryParams :: ActionM [Param] Source #

Get query parameters

jsonData :: FromJSON a => ActionM a Source #

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

files :: ActionM [File] Source #

Get list of uploaded files.

## Modifying the Response and Redirecting

status :: Status -> ActionM () Source #

Set the HTTP response status. Default is 200.

addHeader :: Text -> Text -> ActionM () Source #

Add to the response headers. Header names are case-insensitive.

setHeader :: Text -> Text -> ActionM () Source #

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

redirect :: Text -> ActionM a Source #

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.

text :: Text -> ActionM () Source #

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.

html :: Text -> ActionM () Source #

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.

file :: FilePath -> ActionM () Source #

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`.

json :: ToJSON a => a -> ActionM () Source #

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.

stream :: StreamingBody -> ActionM () Source #

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`.

raw :: ByteString -> ActionM () Source #

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

## Exceptions

raise :: Text -> ActionM a Source #

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

Uncaught exceptions turn into HTTP 500 responses.

raiseStatus :: Status -> Text -> ActionM a Source #

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

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

throw :: Exception e => e -> ActionM a Source #

Throw an exception which can be caught within the scope of the current Action with `rescue` or `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.

rescue :: Exception e => ActionM a -> (e -> ActionM a) -> ActionM a Source #

Catch an exception e.g. a `StatusError` or a user-defined exception.

    raise JustKidding `rescue` (\msg -> text msg)

next :: ActionM () Source #

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 <- captureParam "bar"
      unless (w == "special") next
      text "You made a request to /foo/special"

    get "/foo/:baz" $ do
      w <- captureParam "baz"
      text $ "You made a request to: " <> w

finish :: ActionM a Source #

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 <- captureParam "bar"
      unless (w == "special") finish
      text "You made a request to /foo/special"

Since: 0.10.3

defaultHandler :: ErrorHandler IO -> ScottyM () Source #

Global handler for user-defined exceptions.

liftAndCatchIO :: IO a -> ActionM a Source #

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

data StatusError Source #

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

StatusError Status Text |

#### Instances

Instances details

Exception StatusError Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods toException :: StatusError -> SomeException Source # fromException :: SomeException -> Maybe StatusError Source # displayException :: StatusError -> String Source #
Show StatusError Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods showsPrec :: Int -> StatusError -> ShowS Source # show :: StatusError -> String Source # showList :: [StatusError] -> ShowS Source #
MonadUnliftIO m => MonadError StatusError (ActionT m) Source # | Models the invariant that only `StatusError`s can be thrown and caught.
Instance details Defined in Web.Scotty.Internal.Types Methods throwError :: StatusError -> ActionT m a Source # catchError :: ActionT m a -> (StatusError -> ActionT m a) -> ActionT m a Source #

# Parsing Parameters

type Param = (Text, Text) Source #

class Parsable a where Source #

Minimum implemention: `parseParam`

Minimal complete definition

parseParam

Methods

parseParam :: Text -> Either Text a Source #

Take a `Text` value and parse it as `a`, or fail with a message.

parseParamList :: Text -> Either Text [a] Source #

Default implementation parses comma-delimited lists.

    parseParamList t = mapM parseParam (T.split (== ',') t)

#### Instances

Instances details

Parsable Int16 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int16 Source # parseParamList :: Text -> Either Text [Int16] Source #
Parsable Int32 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int32 Source # parseParamList :: Text -> Either Text [Int32] Source #
Parsable Int64 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int64 Source # parseParamList :: Text -> Either Text [Int64] Source #
Parsable Int8 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int8 Source # parseParamList :: Text -> Either Text [Int8] Source #
Parsable Word16 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word16 Source # parseParamList :: Text -> Either Text [Word16] Source #
Parsable Word32 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word32 Source # parseParamList :: Text -> Either Text [Word32] Source #
Parsable Word64 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word64 Source # parseParamList :: Text -> Either Text [Word64] Source #
Parsable Word8 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word8 Source # parseParamList :: Text -> Either Text [Word8] Source #
Parsable ByteString Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text ByteString Source # parseParamList :: Text -> Either Text [ByteString] Source #
Parsable ByteString Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text ByteString Source # parseParamList :: Text -> Either Text [ByteString] Source #
Parsable Text Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text0 -> Either Text0 Text Source # parseParamList :: Text0 -> Either Text0 [Text] Source #
Parsable Text Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Text Source # parseParamList :: Text -> Either Text [Text] Source #
Parsable Integer Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Integer Source # parseParamList :: Text -> Either Text [Integer] Source #
Parsable Natural Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Natural Source # parseParamList :: Text -> Either Text [Natural] Source #
Parsable () Source # | 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.
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text () Source # parseParamList :: Text -> Either Text [()] Source #
Parsable Bool Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Bool Source # parseParamList :: Text -> Either Text [Bool] Source #
Parsable Char Source # | Overrides default `parseParamList` to parse String.
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Char Source # parseParamList :: Text -> Either Text [Char] Source #
Parsable Double Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Double Source # parseParamList :: Text -> Either Text [Double] Source #
Parsable Float Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Float Source # parseParamList :: Text -> Either Text [Float] Source #
Parsable Int Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int Source # parseParamList :: Text -> Either Text [Int] Source #
Parsable Word Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word Source # parseParamList :: Text -> Either Text [Word] Source #
Parsable a => Parsable [a] Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text [a] Source # parseParamList :: Text -> Either Text [[a]] Source #

readEither :: Read a => Text -> Either Text a Source #

Useful for creating `Parsable` instances for things that already implement `Read`. Ex:

    instance Parsable Int where parseParam = readEither

# Types

type ScottyM = ScottyT IO Source #

type ActionM = ActionT IO Source #

data RoutePattern Source #

#### Instances

Instances details

IsString RoutePattern Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods fromString :: String -> RoutePattern Source #

type File = (Text, FileInfo ByteString) Source #

type Kilobytes = Int Source #

data Handler (m :: Type -> Type) a Source #

Generalized version of `Handler`

Constructors

Exception e => Handler (e -> m a) |

#### Instances

Instances details

Monad m => Functor (Handler m) |
Instance details Defined in Control.Monad.Catch Methods fmap :: (a -> b) -> Handler m a -> Handler m b Source # (<$) :: a -> Handler m b -> Handler m a Source #

data ScottyState m Source #

#### Instances

Instances details

Default (ScottyState m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods def :: ScottyState m Source #

defaultScottyState :: ScottyState m Source #