scottyT Run a scotty application using the warp server. NB: scotty p === scottyT p id
:: a typeCtrl KGHC 10.0.0.20260917 · lts/ghc-10.0.x · fc4e598 · 2026-10-11
Modulescotty-0.30Haskell2010
It should be noted that most of the code snippets below depend on the OverloadedStrings language pragma.
The functions in this module allow an arbitrary monad to be embedded in Scotty's monad transformer stack, e.g. for complex endpoint configuration, interacting with databases etc.
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.
scotty serversscottyT Run a scotty application using the warp server. NB: scotty p === scottyT p id
scottyOptsT Run a scotty application using the warp server, passing extra options. NB: scottyOpts opts === scottyOptsT opts id
Run a scotty application using the warp server, passing extra options, and listening on the provided socket. NB: scottySocket opts sock === scottySocketT opts sock id
Optionsverbose :: Int0 = silent, 1(def) = startup banner
settings :: SettingsWarp 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.
jsonMode :: BoolIf True, return JSON error responses instead of HTML
scottyAppT Turn a scotty application into a WAI Application, which can be run with any WAI handler. NB: scottyApp === scottyAppT id
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.
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.
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.
:{let server = S.get "/foo/:bar" (S.pathParam "bar" >>= S.text) in do withScotty server $ curl "http://localhost:3000/foo/something":}"something"
Add a route that matches regardless of the HTTP verb.
Specify an action to take if nothing else is found. Note: this _always_ matches, so should generally be the last route specified.
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.
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.
Match requests using a regular expression. Named captures are not yet supported.
:{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"
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.
:{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"
Build a route that requires the requested path match exactly, without captures.
Get the Request object.
Get a request header. Header name is case-insensitive.
Get all the request headers. Header names are case-insensitive.
Get the request body.
NB This loads the whole request body in memory at once.
Parse the request body as a JSON object and return it.
If the JSON object is malformed, this sets the status to 400 Bad Request, and throws an exception.
If the JSON fails to parse, this sets the status to 422 Unprocessable Entity.
These status codes are as per https://www.restapitutorial.com/httpstatuscodes.html.
NB : Internally this uses body.
Parse the request body as x-www-form-urlencoded form data and return it.
The form is parsed using urlDecodeAsForm. If that returns Left, the
status is set to 400 and an exception is thrown.
Look up 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.20
Synonym for pathParam
Look up 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
Look up 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
Get path parameters
Get path parameters
Get form parameters
Get query parameters
Get list of uploaded files.
NB: Loads all file contents in memory with options defaultParseRequestBodyOptions
filesOpts :: MonadUnliftIO m=> ParseRequestBodyOptions-> ([Param] -> [File FilePath] -> ActionT m a)temp files validation, storage etc
-> ActionT m aGet list of uploaded temp files and form parameters decoded from multipart payloads.
NB the temp files are deleted when the continuation exits.
Set the HTTP response status.
Add to the response headers. Header names are case-insensitive.
Set one of the response headers. Will override any previously set value for that header. Header names are case-insensitive.
Synonym for redirect302. If you are unsure which redirect to use, you probably want this one.
redirect "http://www.google.com"OR
redirect "/foo/bar"Redirect to given URL with status 300 (Multiple Choices). Like throwing an uncatchable exception. Any code after the call to redirect will not be run.
Redirect to given URL with status 301 (Moved Permanently). Like throwing an uncatchable exception. Any code after the call to redirect will not be run.
Redirect to given URL with status 302 (Found). Like throwing an uncatchable exception. Any code after the call to redirect will not be run.
Redirect to given URL with status 303 (See Other). Like throwing an uncatchable exception. Any code after the call to redirect will not be run.
Redirect to given URL with status 304 (Not Modified). Like throwing an uncatchable exception. Any code after the call to redirect will not be run.
Redirect to given URL with status 307 (Temporary Redirect). Like throwing an uncatchable exception. Any code after the call to redirect will not be run.
Redirect to given URL with status 308 (Permanent Redirect). Like throwing an uncatchable exception. Any code after the call to redirect will not be run.
Note: only one of these should be present in any given route
definition, as they completely replace the current Response body.
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. Setting a status code will have no effect because Warp will overwrite that to 200 (see sendResponse).
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.
Set the body of the response to a Source. Doesn't set the "Content-Type" header, so you probably want to do that on your own with setHeader.
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.
Nest a whole WAI application inside a Scotty handler. See Web.Scotty for further documentation
Access the HTTP headers of the Response
SINCE 0.21
Access the HTTP Status of the Response
SINCE 0.21
Access the content of the Response
SINCE 0.21
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.
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: " <> wFinish the execution of the current action. Like throwing an uncatchable exception. Any code after the call to finish will not be run.
Since: 0.10.3
Global handler for user-defined exceptions.
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).
import Control.Monad.Trans.State -- from the "transformers" library
printState :: Show s => StateT s IO ()
printState = do
state <- get
liftIO $ print stateHad 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
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.
Thrown e.g. when a request is too large
RequestTooLargeMalformedJSON ByteString TextFailedToParseJSON ByteString TextMalformedForm TextPathParameterNotFound TextQueryParameterNotFound TextFormFieldNotFound TextFailedToParseParameter Text Text TextWarpRequestException InvalidRequestWaiRequestParseException RequestParseExceptionResourceTException InvalidAccessShow ScottyExceptionDefined in scotty-0.30 · Web.Scotty.Internal.TypesException ScottyExceptionDefined in scotty-0.30 · Web.Scotty.Internal.TypesMinimum implemention: parseParam
parseParam :: Text -> Either Text aTake a Text value and parse it as a, or fail with a message.
parseParamList :: Text -> Either Text [a]Default implementation parses comma-delimited lists.
parseParamList t = mapM parseParam (T.split (== ',') t)Parsable ByteStringDefined in scotty-0.30 · Web.Scotty.ActionParsable ByteStringDefined in scotty-0.30 · Web.Scotty.ActionParsable IntegerDefined in scotty-0.30 · Web.Scotty.ActionParsable NaturalDefined in scotty-0.30 · Web.Scotty.ActionParsable Int16Defined in scotty-0.30 · Web.Scotty.ActionParsable Int32Defined in scotty-0.30 · Web.Scotty.ActionParsable Int64Defined in scotty-0.30 · Web.Scotty.ActionParsable Int8Defined in scotty-0.30 · Web.Scotty.ActionParsable BoolDefined in scotty-0.30 · Web.Scotty.ActionParsable CharDefined in scotty-0.30 · Web.Scotty.ActionOverrides default parseParamList to parse String.
Parsable DoubleDefined in scotty-0.30 · Web.Scotty.ActionParsable FloatDefined in scotty-0.30 · Web.Scotty.ActionParsable IntDefined in scotty-0.30 · Web.Scotty.ActionParsable WordDefined in scotty-0.30 · Web.Scotty.ActionParsable Word16Defined in scotty-0.30 · Web.Scotty.ActionParsable Word32Defined in scotty-0.30 · Web.Scotty.ActionParsable Word64Defined in scotty-0.30 · Web.Scotty.ActionParsable Word8Defined in scotty-0.30 · Web.Scotty.ActionParsable TextDefined in scotty-0.30 · Web.Scotty.ActionParsable TextDefined in scotty-0.30 · Web.Scotty.ActionParsable UTCTimeDefined in scotty-0.30 · Web.Scotty.Actionparse 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.30 · Web.Scotty.ActionChecks 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.30 · Web.Scotty.ActionIsString RoutePatternDefined in scotty-0.30 · Web.Scotty.Internal.TypesType parameter t is the file content. Could be () when not needed or a FilePath for temp files instead.
Monad (ScottyT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesFunctor (ScottyT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesApplicative (ScottyT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesSemigroup a => Semigroup (ScottyT m a)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonoid a => Monoid (ScottyT m a)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadTrans ActionTDefined in scotty-0.30 · Web.Scotty.Internal.TypesMonadTransControl ActionTDefined in scotty-0.30 · Web.Scotty.Internal.TypesMonadReader r m => MonadReader r (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadBase b m => MonadBase b (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadBaseControl b m => MonadBaseControl b (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonad m => Monad (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesFunctor m => Functor (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadIO m => MonadFail (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadFail instance for ActionT that converts fail calls into Scotty exceptions which allows these failures to be caught by Scotty's error handling system and properly returned as HTTP 500 responses. The instance throws a StringException containing both the failure message and a call stack for debugging purposes.
Applicative m => Applicative (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadUnliftIO m => Alternative (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.Typesempty throws ActionError AENext, whereas (<|>) catches any ActionErrors or StatusErrors in the first action and proceeds to the second one.
MonadUnliftIO m => MonadPlus (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadIO m => MonadIO (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadCatch m => MonadCatch (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadThrow m => MonadThrow (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.TypesMonadUnliftIO m => MonadUnliftIO (ActionT m)Defined in scotty-0.30 · Web.Scotty.Internal.Types(Monad m, Semigroup a) => Semigroup (ActionT m a)Defined in scotty-0.30 · Web.Scotty.Internal.Types(Monad m, Monoid a) => Monoid (ActionT m a)Defined in scotty-0.30 · Web.Scotty.Internal.Typestype StM (ActionT m) a = StM (ReaderT ActionEnv m) aDefined in scotty-0.30 · Web.Scotty.Internal.Typestype StT ActionT a = StT (ReaderT ActionEnv) aDefined in scotty-0.30 · Web.Scotty.Internal.TypesmakeSimpleCookie and setCookie combined.
Lookup one cookie name
Returns all cookies
Browsers don't directly delete a cookie, but setting its expiry to a past date (e.g. the UNIX epoch) ensures that the cookie will be invalidated (whether and when it will be actually deleted by the browser seems to be browser-dependent).
Construct a simple cookie (an UTF-8 string pair with default cookie options)
Represents a session containing an ID, expiration time, and content.
SessionsessId :: SessionIdUnique identifier for the session.
sessExpiresAt :: UTCTimeExpiration time of the session.
sessContent :: aContent stored in the session.
Type alias for session identifiers.
Type for session storage, a transactional variable containing a map of session IDs to sessions.
Creates a new session jar and starts a background thread to maintain it.
createUserSession Creates a new session for a user, storing the content and setting a cookie.
Creates a new session with a generated ID, sets its expiration, | and adds it to the session jar.
Reads the content of the current user's session.
Reads the content of a session by its ID.
Retrieves the current user's session based on the "sess_id" cookie. | Returns `Left SessionStatus` if the session is expired or does not exist.
Retrieves a session by its ID from the session jar.
Adds or overwrites a new session to the session jar.
Deletes a session by its ID from the session jar.
Continuously removes expired sessions from the session jar.