### Basic Scotty Server Setup
Source: https://context7.com/scotty-web/scotty/llms.txt
This snippet demonstrates the fundamental setup for a Scotty web server. It initializes the server on port 3000 and defines two basic routes: a GET request for the root ('/') returning plain text, and a GET request for '/:word' that captures a word from the path and includes it in an HTML response. Dependencies include 'Web.Scotty'.
```haskell
{-# LANGUAGE OverloadedStrings \}
import Web.Scotty
main :: IO ()
main = scotty 3000 $ do
get "/" $ do
text "Hello World!"
get "/:word" $ do
beam <- pathParam "word"
html $ mconcat ["
Scotty, ", beam, " me up!
"]
```
--------------------------------
### API Request Examples using curl
Source: https://context7.com/scotty-web/scotty/llms.txt
Demonstrates making POST and GET requests to a Scotty application using the curl command-line tool. Includes examples for creating a user with JSON data and fetching random data.
```bash
curl -X POST -H "Content-Type: application/json" \
-d '{"userId":5,"userName":"Bob","userEmail":"bob@test.com"}' \
localhost:3000/user/create
# Output: {"created":"Bob","id":5}
curl localhost:3000/random
# Output: [45,12,78,34,...]
```
--------------------------------
### Basic Server Setup
Source: https://context7.com/scotty-web/scotty/llms.txt
This section demonstrates how to set up a basic Scotty web server, define a root route, and a route with a path parameter.
```APIDOC
## GET /
### Description
Handles GET requests to the root path and returns a simple text response.
### Method
GET
### Endpoint
/
### Parameters
### Request Example
### Response
#### Success Response (200)
- **text** (string) - The text response body.
#### Response Example
```
Hello World!
```
## GET /:word
### Description
Handles GET requests to a path with a dynamic segment, capturing the segment as a path parameter and embedding it in an HTML response.
### Method
GET
### Endpoint
/:word
### Parameters
#### Path Parameters
- **word** (string) - The dynamic segment in the URL.
### Request Example
### Response
#### Success Response (200)
- **html** (string) - An HTML response containing the captured path parameter.
#### Response Example
```html
Scotty, Enterprise me up!
```
```
--------------------------------
### Running Scotty Example with Stack
Source: https://github.com/scotty-web/scotty/blob/master/README.md
This command demonstrates how to execute a Scotty example application using the `stack` build tool. It's an alternative to running standalone Haskell scripts with `runghc`.
```bash
stack exec -- scotty-basic
```
--------------------------------
### Scotty Route Definitions with HTTP Verbs
Source: https://context7.com/scotty-web/scotty/llms.txt
This example showcases defining routes for various HTTP methods (GET, POST, PUT, DELETE, PATCH) in Scotty. It includes examples of capturing path parameters, reading request bodies, sending JSON responses, and setting status codes. It also demonstrates a 'matchAny' route for any HTTP verb. Dependencies include 'Web.Scotty' and 'Network.HTTP.Types'.
```haskell
{-# LANGUAGE OverloadedStrings \}
import Web.Scotty
import Network.HTTP.Types (status302)
main :: IO ()
main = scotty 3000 $ do
-- GET route with path parameter
get "/foo/:bar/required" $ do
v <- pathParam "bar"
html $ mconcat ["", v, "
"]
-- POST route reading request body
post "/readbody" $ do
b <- body
text $ decodeUtf8 b
-- PUT route
put "/update/:id" $ do
userId <- pathParam "id"
json $ object ["updated" .= (userId :: Int)]
-- DELETE route
delete "/remove/:id" $ do
itemId <- pathParam "id"
status status200
text $ "Deleted item " <> itemId
-- PATCH route
patch "/modify/:resource" $ do
res <- pathParam "resource"
text $ "Modified " <> res
-- Match any HTTP verb
matchAny "/wildcard" $ do
text "This matches GET, POST, PUT, DELETE, etc."
```
--------------------------------
### Interacting with Scotty Server via Curl
Source: https://github.com/scotty-web/scotty/blob/master/README.md
These examples show how to interact with a running Scotty web server using the `curl` command-line tool. The first example fetches the root path, and the second demonstrates fetching a path with a query parameter.
```bash
curl localhost:3000
```
```bash
curl localhost:3000/foo_query?p=42
```
--------------------------------
### Route Definitions with HTTP Verbs
Source: https://context7.com/scotty-web/scotty/llms.txt
This section covers defining routes for various HTTP methods (GET, POST, PUT, DELETE, PATCH) and using `matchAny` for any HTTP verb.
```APIDOC
## GET /foo/:bar/required
### Description
Handles GET requests with a required path parameter.
### Method
GET
### Endpoint
/foo/:bar/required
### Parameters
#### Path Parameters
- **bar** (string) - Required path parameter.
### Request Example
### Response
#### Success Response (200)
- **html** (string) - HTML response containing the path parameter.
#### Response Example
```html
something
```
## POST /readbody
### Description
Handles POST requests, reading and returning the raw request body.
### Method
POST
### Endpoint
/readbody
### Parameters
#### Request Body
- **(raw)** (string) - The raw request body.
### Request Example
```
test data
```
### Response
#### Success Response (200)
- **text** (string) - The raw request body.
#### Response Example
```
test data
```
## PUT /update/:id
### Description
Handles PUT requests with a path parameter, returning a JSON object indicating an update.
### Method
PUT
### Endpoint
/update/:id
### Parameters
#### Path Parameters
- **id** (integer) - The ID of the resource to update.
### Request Example
### Response
#### Success Response (200)
- **json** (object) - A JSON object confirming the update.
#### Response Example
```json
{
"updated": 123
}
```
## DELETE /remove/:id
### Description
Handles DELETE requests with a path parameter, returning a success status and a confirmation message.
### Method
DELETE
### Endpoint
/remove/:id
### Parameters
#### Path Parameters
- **id** (string) - The ID of the item to remove.
### Request Example
### Response
#### Success Response (200)
- **status** (HTTP Status Code) - Set to 200.
- **text** (string) - A confirmation message indicating the item was deleted.
#### Response Example
```
Deleted item 42
```
## PATCH /modify/:resource
### Description
Handles PATCH requests with a path parameter, indicating a modification.
### Method
PATCH
### Endpoint
/modify/:resource
### Parameters
#### Path Parameters
- **resource** (string) - The name of the resource to modify.
### Request Example
### Response
#### Success Response (200)
- **text** (string) - A confirmation message indicating the resource was modified.
#### Response Example
```
Modified "some_resource"
```
## matchAny /wildcard
### Description
Handles requests for any HTTP verb to the specified path.
### Method
ANY (GET, POST, PUT, DELETE, etc.)
### Endpoint
/wildcard
### Parameters
### Request Example
### Response
#### Success Response (200)
- **text** (string) - A response indicating the wildcard matched.
#### Response Example
```
This matches GET, POST, PUT, DELETE, etc.
```
```
--------------------------------
### Scotty JSON Data Handling
Source: https://context7.com/scotty-web/scotty/llms.txt
This example demonstrates handling JSON data with Scotty. It shows how to define a data type for JSON serialization/deserialization using Aeson, send JSON responses for GET requests, parse JSON request bodies for POST requests, return JSON arrays, and handle complex JSON structures with type annotations. Dependencies include 'Web.Scotty', 'Data.Aeson', 'GHC.Generics', and 'System.Random'.
```haskell
{-# LANGUAGE OverloadedStrings \}
{-# LANGUAGE DeriveGeneric \}
import Web.Scotty
import Data.Aeson (FromJSON, ToJSON)
import GHC.Generics
import System.Random (newStdGen, randomRs)
data User = User
{
userId :: Int
, userName :: String
, userEmail :: String
}
deriving (Generic, FromJSON, ToJSON)
main :: IO ()
main = scotty 3000 $ do
-- Return JSON response
get "/user/:id" $ do
uid <- pathParam "id"
json $ User uid "Alice" "alice@example.com"
-- Parse JSON request body
post "/user/create" $ do
user <- jsonData :: ActionM User
json $ object ["created" .= userName user, "id" .= userId user]
-- Return array as JSON
get "/random" $ do
g <- liftIO newStdGen
json $ take 20 $ randomRs (1::Int, 100) g
-- Complex JSON with type annotation
get "/ints/:is" $ do
is <- pathParam "is"
json $ [(1::Int)..10] ++ is
```
--------------------------------
### Manage Cookies and Sessions with Scotty Haskell
Source: https://context7.com/scotty-web/scotty/llms.txt
This snippet demonstrates how to set, read, delete cookies, and manage user sessions using the Scotty web framework in Haskell. It includes examples for handling login, protected routes, and logout. Dependencies include Web.Scotty and Data.Text.
```haskell
{-# LANGUAGE OverloadedStrings #}
import Web.Scotty
import qualified Data.Text as T
main :: IO ()
main = do
sessionJar <- liftIO createSessionJar :: IO (SessionJar T.Text)
scotty 3000 $ do
-- Set a simple cookie
get "/set-cookie" $ do
name <- queryParam "name"
value <- queryParam "value"
setSimpleCookie name value
text "Cookie set!"
-- Read cookies
get "/show-cookies" $ do
cookies <- getCookies
json cookies
-- Delete a cookie
get "/delete-cookie/:name" $ do
name <- pathParam "name"
deleteCookie name
text $ "Deleted cookie: " <> name
-- Login with session
post "/login" $ do
username <- formParam "username" :: ActionM String
password <- formParam "password" :: ActionM String
if username == "alice" && password == "secret"
then do
_ <- createUserSession sessionJar Nothing username
text "Login successful!"
else do
status status401
text "Invalid credentials"
-- Protected route checking session
get "/dashboard" $ do
userResult <- readUserSession sessionJar
case userResult of
Left _ -> do
status status401
text "Not authenticated"
Right username -> do
text $ "Welcome, " <> LT.fromStrict username
-- Logout
post "/logout" $ do
deleteCookie "sess_id"
text "Logged out"
```
--------------------------------
### Custom Monad Stack with Global State in Scotty Haskell
Source: https://context7.com/scotty-web/scotty/llms.txt
This Haskell snippet illustrates embedding the Scotty web framework within a custom monad transformer stack (WebM) for managing global application state using TVars. It includes examples for accessing and modifying shared state within web routes. Dependencies include Web.Scotty.Trans, Control.Concurrent.STM, Control.Monad.IO.Unlift, and Control.Monad.Reader.
```haskell
{-# LANGUAGE OverloadedStrings #}
{-# LANGUAGE GeneralizedNewtypeDeriving #}
import Web.Scotty.Trans
import Control.Concurrent.STM
import Control.Monad.IO.Unlift (MonadUnliftIO)
import Control.Monad.Reader
newtype AppState = AppState { tickCount :: Int }
newtype WebM a = WebM { runWebM :: ReaderT (TVar AppState) IO a }
deriving (Applicative, Functor, Monad, MonadIO, MonadReader (TVar AppState), MonadUnliftIO)
webM :: MonadTrans t => WebM a -> t WebM a
webM = lift
gets :: (AppState -> b) -> WebM b
gets f = ask >>= liftIO . readTVarIO >>= return . f
modify :: (AppState -> AppState) -> WebM ()
modify f = ask >>= liftIO . atomically . flip modifyTVar' f
main :: IO ()
main = do
sync <- newTVarIO (AppState 0)
let runActionToIO m = runReaderT (runWebM m) sync
scottyT 3000 runActionToIO $ do
get "/" $ do
c <- webM $ gets tickCount
text $ fromString $ show c
get "/increment" $ do
webM $ modify $ \st -> st { tickCount = tickCount st + 1 }
redirect "/"
post "/add/:amount" $ do
n <- pathParam "amount"
webM $ modify $ \st -> st { tickCount = tickCount st + n }
c <- webM $ gets tickCount
json $ object ["count" .= c]
```
--------------------------------
### Scotty Query and Form Parameters
Source: https://context7.com/scotty-web/scotty/llms.txt
This snippet illustrates how to extract query string parameters and form data in Scotty. It covers retrieving single query parameters, optional parameters using 'queryParamMaybe', and form parameters using 'formParam'. It also shows how to get all query parameters as a JSON object. Dependencies include 'Web.Scotty'.
```haskell
{-# LANGUAGE OverloadedStrings \}
import Web.Scotty
main :: IO ()
main = scotty 3000 $ do
-- Query parameter extraction
get "/foo_query" $ do
v <- queryParam "p"
html $ mconcat ["", v, "
"]
-- Optional parameter with Maybe
get "/search" $ do
term <- queryParamMaybe "q"
limit <- queryParamMaybe "limit" :: ActionM (Maybe Int)
case term of
Nothing -> text "No search term provided"
Just t -> text $ "Searching for: " <> t
-- Form parameter extraction
post "/submit" $ do
username <- formParam "username"
password <- formParam "password"
text $ "Received: " <> username
-- Get all query parameters
get "/all-params" $ do
params <- queryParams
json params
```
--------------------------------
### Scotty Middleware and WAI Integration
Source: https://context7.com/scotty-web/scotty/llms.txt
Shows how to apply WAI middleware (like request logging, static file serving, and gzip compression) to a Scotty application. It also demonstrates converting a Scotty app into a WAI application for use with other WAI handlers. Dependencies include 'scotty', 'wai-extra', and 'wai-middleware-request-logger'.
```haskell
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Network.Wai.Middleware.RequestLogger (logStdoutDev)
import Network.Wai.Middleware.Static (staticPolicy, addBase, noDots, (>->))
import Network.Wai.Middleware.Gzip (gzip, def)
import Network.Wai.Handler.Warp (run)
main :: IO ()
main = scotty 3000 $ do
-- Middleware runs top-down
middleware logStdoutDev
middleware $ staticPolicy (noDots >-> addBase "static")
middleware $ gzip def
get "/" $ do
text "Hello with middleware!"
get "/api/data" $ do
json $ object ["status" .= ("ok" :: String)]
-- Converting to WAI Application
mainWAI :: IO ()
mainWAI = do
app <- scottyApp $ do
get "/" $ text "WAI app"
-- Can now use with any WAI handler
run 3000 app
```
--------------------------------
### User Creation API
Source: https://context7.com/scotty-web/scotty/llms.txt
Creates a new user with the provided user details.
```APIDOC
## POST /user/create
### Description
Creates a new user with the provided user details.
### Method
POST
### Endpoint
/user/create
### Parameters
#### Request Body
- **userId** (integer) - Required - The unique identifier for the user.
- **userName** (string) - Required - The name of the user.
- **userEmail** (string) - Required - The email address of the user.
### Request Example
```json
{
"userId": 5,
"userName": "Bob",
"userEmail": "bob@test.com"
}
```
### Response
#### Success Response (200)
- **created** (string) - The name of the created user.
- **id** (integer) - The ID of the created user.
#### Response Example
```json
{
"created": "Bob",
"id": 5
}
```
```
--------------------------------
### Basic Scotty Web Server in Haskell
Source: https://github.com/scotty-web/scotty/blob/master/README.md
This snippet demonstrates a fundamental Scotty application. It sets up a web server on port 3000 and defines a route that captures a word from the URL path and displays it in an HTML heading. It requires the `Web.Scotty` library.
```haskell
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
main = scotty 3000 $
get "/:word" $ do
beam <- pathParam "word"
html $ mconcat ["Scotty, ", beam, " me up!
"]
```
--------------------------------
### Scotty Route Pattern Matching
Source: https://context7.com/scotty-web/scotty/llms.txt
Illustrates advanced route pattern matching in Scotty, including capture groups, regular expressions, function-based matching, and literal paths. It also shows how to define a catch-all 'notFound' handler. Dependencies include 'scotty' and 'text'.
```haskell
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import qualified Data.Text as T
main :: IO ()
main = scotty 3000 $ do
-- Standard capture pattern
get (capture "/user/:id") $ do
userId <- pathParam "id"
text $ "User ID: " <> userId
-- Regex pattern matching
get (regex "^/f(.*)r$") $ do
cap <- pathParam "1" -- Captured groups are numbered
text $ "Matched: " <> cap
-- Function-based pattern
get (function $ \req ->
if requestMethod req == "GET"
then Just [("version", T.pack $ show $ httpVersion req)]
else Nothing) $ do
v <- pathParam "version"
text $ "HTTP Version: " <> v
-- Literal pattern (no captures)
get (literal "/exact/path/only") $ do
text "This only matches exactly"
-- Catch-all notFound handler
notFound $ do
status status404
html "404 - Page Not Found
"
```
--------------------------------
### Run Scotty Commands with Bash
Source: https://context7.com/scotty-web/scotty/llms.txt
This snippet shows how to use curl commands to interact with a Scotty web application. It demonstrates setting cookies, viewing cookies, logging in, and accessing a protected dashboard route. Assumes the Scotty application is running on localhost:3000.
```bash
curl "localhost:3000/set-cookie?name=theme&value=dark"
# Output: Cookie set!
curl -b cookies.txt localhost:3000/show-cookies
# Output: [["theme","dark"]]
curl -X POST -d "username=alice&password=secret" -c session.txt localhost:3000/login
# Output: Login successful!
curl -b session.txt localhost:3000/dashboard
# Output: Welcome, alice
```
--------------------------------
### Bash: Testing Exception Handling Routes
Source: https://context7.com/scotty-web/scotty/llms.txt
Tests the exception handling routes defined in the Haskell Scotty application. Demonstrates accessing protected routes, routes with validation errors, and special word routes.
```bash
curl localhost:3000/protected
# Output: Access Denied
# Status: 403
curl localhost:3000/safe/-5
# Output: Caught locally: Value must be positive
curl localhost:3000/special/magic
# Output: You found the magic word!
```
--------------------------------
### Exception Handling APIs
Source: https://context7.com/scotty-web/scotty/llms.txt
Demonstrates custom exception types and global/local error handlers.
```APIDOC
## Exception Handling APIs
### Description
These endpoints demonstrate custom exception types and global/local error handlers within the Scotty framework.
### GET /protected
#### Description
This route throws a `Forbidden` exception, which is caught by the global error handler.
#### Method
GET
#### Endpoint
/protected
#### Response
##### Success Response (403)
- **HTML content** - "Access Denied
"
#### Response Example
```html
Access Denied
```
### GET /safe/:val
#### Description
This route handles validation errors locally. If the `val` parameter is negative, it throws a `ValidationError` that is caught and handled within the route.
#### Method
GET
#### Endpoint
/safe/:val
#### Parameters
##### Path Parameters
- **val** (integer) - Required - The value to check.
#### Response
##### Success Response (200)
- **JSON object** - Contains the validated value.
##### Error Response (handled locally)
- **Text content** - "Caught locally: Value must be positive"
#### Response Example (Success)
```json
{
"value": -5
}
```
#### Response Example (Error)
```
Caught locally: Value must be positive
```
### GET /special/:word
#### Description
This endpoint uses `next` to match patterns. If the `word` is "magic", it executes the first handler; otherwise, it falls through to the second handler.
#### Method
GET
#### Endpoint
/special/:word
#### Parameters
##### Path Parameters
- **word** (string) - Required - The word to match.
#### Response
##### Success Response (200)
- **Text content** - "You found the magic word!" or "Ordinary word: [word]"
#### Response Example (Magic Word)
```
You found the magic word!
```
#### Response Example (Ordinary Word)
```
Ordinary word: hello
```
```
--------------------------------
### Cookie and Session Management
Source: https://context7.com/scotty-web/scotty/llms.txt
Demonstrates how to set, read, and delete cookies using Scotty. It also shows how to implement user login, session management, and protected routes.
```APIDOC
## Cookie and Session Management
Setting, reading, and managing cookies and user sessions.
### GET /set-cookie
**Description**: Sets a simple cookie.
**Query Parameters**:
- **name** (string) - Required - The name of the cookie.
- **value** (string) - Required - The value of the cookie.
### GET /show-cookies
**Description**: Retrieves and displays all cookies.
### GET /delete-cookie/:name
**Description**: Deletes a specific cookie by its name.
**Path Parameters**:
- **name** (string) - Required - The name of the cookie to delete.
### POST /login
**Description**: Handles user login by validating username and password, and creating a user session.
**Request Body**:
- **username** (string) - Required - The user's username.
- **password** (string) - Required - The user's password.
**Response**:
- **200 OK**: Login successful.
- **401 Unauthorized**: Invalid credentials.
### GET /dashboard
**Description**: A protected route that checks for an active user session. Requires authentication.
**Response**:
- **200 OK**: Welcome message with the username if authenticated.
- **401 Unauthorized**: If the user is not authenticated.
### POST /logout
**Description**: Logs the user out by deleting the session cookie.
### Request Example: Set Cookie
```bash
curl "localhost:3000/set-cookie?name=theme&value=dark"
```
### Request Example: Show Cookies
```bash
curl -b cookies.txt localhost:3000/show-cookies
```
### Request Example: Delete Cookie
```bash
curl /delete-cookie/theme
```
### Request Example: Login
```bash
curl -X POST -d "username=alice&password=secret" -c session.txt localhost:3000/login
```
### Request Example: Access Dashboard
```bash
curl -b session.txt localhost:3000/dashboard
```
### Response Example: Show Cookies
```json
[["theme","dark"]]
```
```
--------------------------------
### Query and Form Parameters
Source: https://context7.com/scotty-web/scotty/llms.txt
Demonstrates how to extract query parameters and form data from incoming requests.
```APIDOC
## GET /foo_query
### Description
Retrieves a specific query parameter from the URL.
### Method
GET
### Endpoint
/foo_query
### Parameters
#### Query Parameters
- **p** (string) - The query parameter to retrieve.
### Request Example
```
localhost:3000/foo_query?p=42
```
### Response
#### Success Response (200)
- **html** (string) - HTML response containing the value of the 'p' query parameter.
#### Response Example
```html
42
```
## GET /search
### Description
Retrieves optional query parameters 'q' (search term) and 'limit'.
### Method
GET
### Endpoint
/search
### Parameters
#### Query Parameters
- **q** (string) - Optional search term.
- **limit** (integer) - Optional limit for search results.
### Request Example
```
localhost:3000/search?q=haskell&limit=10
```
### Response
#### Success Response (200)
- **text** (string) - A message indicating the search term or that no term was provided.
#### Response Example
```
Searching for: haskell
```
## POST /submit
### Description
Handles POST requests and extracts form parameters.
### Method
POST
### Endpoint
/submit
### Parameters
#### Request Body
- **username** (string) - The username submitted in the form.
- **password** (string) - The password submitted in the form.
### Request Example
```bash
curl -X POST -d "username=alice&password=secret" localhost:3000/submit
```
### Response
#### Success Response (200)
- **text** (string) - A confirmation message including the received username.
#### Response Example
```
Received: alice
```
## GET /all-params
### Description
Retrieves and returns all query parameters as a JSON object.
### Method
GET
### Endpoint
/all-params
### Parameters
### Request Example
### Response
#### Success Response (200)
- **json** (object) - An object containing all query parameters.
#### Response Example
```json
{
"param1": "value1",
"param2": "value2"
}
```
```
--------------------------------
### Cabal Project Configuration for regex-posix
Source: https://github.com/scotty-web/scotty/blob/master/README.md
This snippet illustrates how to update the `constraints` section in a `cabal.project.local` file to resolve issues with the `regex-posix` library. It specifies a flag to enable a particular build option.
```cabal
constraints:
regex-posix +_regex-posix-clib
```
--------------------------------
### Curl: Testing Scotty Text, Header, and Redirect Responses
Source: https://context7.com/scotty-web/scotty/llms.txt
These bash commands demonstrate how to test Scotty web application responses using `curl`. They show how to retrieve plain text, inspect response headers (like custom ones), and verify HTTP redirects.
```bash
curl localhost:3000/text
# Output: Plain text response
curl -I localhost:3000/api/resource
# Shows: X-Custom-Header: value
curl localhost:3000/old-path
# Redirects (301) to /new-path
```
--------------------------------
### Scotty: Plain Text, HTML, File Download, and Custom Status Responses
Source: https://context7.com/scotty-web/scotty/llms.txt
This Haskell code snippet demonstrates creating basic Scotty routes for serving plain text, HTML, initiating a file download with specific headers, and returning a custom HTTP status code with a JSON error message. It utilizes Scotty's built-in functions for response handling.
```haskell
{-# LANGUAGE OverloadedStrings #}
import Web.Scotty
import Network.HTTP.Types
main :: IO ()
main = scotty 3000 $ do
-- Plain text response
get "/text" $ do
text "Plain text response"
-- HTML response
get "/html" $ do
html "HTML Response
"
-- File download
get "/download" $ do
setHeader "Content-Type" "application/pdf"
setHeader "Content-Disposition" "attachment; filename=document.pdf"
file "files/document.pdf"
-- Custom status
get "/error" $ do
status status500
json $ object ["error" .= ("Internal error" :: String)]
```
--------------------------------
### Haskell Stack Configuration for regex-posix
Source: https://github.com/scotty-web/scotty/blob/master/README.md
This YAML snippet shows how to configure `stack.yaml` to handle potential compilation issues with the `regex-posix` library on Windows. It adds `regex-posix-clib-2.7` to `extra-deps` and enables a specific flag.
```yaml
extra-deps:
- regex-posix-clib-2.7
flags:
regex-posix:
_regex-posix-clib: true
```
--------------------------------
### Custom Monad Stack with Global State
Source: https://context7.com/scotty-web/scotty/llms.txt
Illustrates how to embed Scotty into a custom monad transformer stack, enabling global state management using STM and ReaderT.
```APIDOC
## Custom Monad Stack with Global State
Embedding Scotty into a custom monad transformer stack for global state management.
### GET /
**Description**: Retrieves and displays the current value of the global tick count.
**Response**: Returns the tick count as text.
### GET /increment
**Description**: Increments the global tick count by one and redirects to the root path.
### POST /add/:amount
**Description**: Adds a specified amount to the global tick count.
**Path Parameters**:
- **amount** (integer) - Required - The amount to add to the tick count.
**Response**: Returns a JSON object with the updated tick count.
### Request Example: Get Tick Count
```bash
curl localhost:3000/
```
### Request Example: Increment Tick Count
```bash
curl localhost:3000/increment
```
### Request Example: Add Amount
```bash
curl -X POST localhost:3000/add/5
```
### Response Example: Add Amount
```json
{"count":6}
```
```
--------------------------------
### Scotty: Adding Custom Headers, JSON Response, and Redirects
Source: https://context7.com/scotty-web/scotty/llms.txt
This Haskell code illustrates how to add custom HTTP headers to a response, return a JSON object, and handle HTTP redirects using the Scotty framework. It showcases route definitions for an API resource and old/new paths for redirection.
```haskell
{-# LANGUAGE OverloadedStrings #}
import Web.Scotty
import Network.HTTP.Types
main :: IO ()
main = scotty 3000 $ do
-- Add headers
get "/api/resource" $ do
addHeader "X-Custom-Header" "value"
addHeader "X-Rate-Limit" "100"
json $ object ["data" .= ("resource" :: String)]
-- Redirects
get "/old-path" $ redirect301 "/new-path"
get "/new-path" $ text "New location"
```
--------------------------------
### Scotty with ReaderT Configuration
Source: https://context7.com/scotty-web/scotty/llms.txt
Demonstrates using the ReaderT monad transformer to provide application configuration (environment, API key, connection limits) to Scotty routes. It defines a Config data type and a ConfigM newtype for the monadic context. Dependencies include 'scotty-trans', 'mtl', and 'unliftio'.
```haskell
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty.Trans
import Control.Monad.Reader
import Control.Monad.IO.Unlift (MonadUnliftIO)
data Config = Config
{ environment :: String
, apiKey :: String
, maxConnections :: Int
} deriving (Show)
newtype ConfigM a = ConfigM
{ runConfigM :: ReaderT Config IO a
}
deriving (Applicative, Functor, Monad, MonadIO, MonadReader Config, MonadUnliftIO)
application :: ScottyT ConfigM ()
application = do
get "/" $ do
env <- lift $ asks environment
text $ pack $ "Running in: " ++ env
get "/config" $ do
cfg <- lift ask
json $ object
["environment" .= environment cfg
,"maxConnections" .= maxConnections cfg
]
get "/api/data" $ do
key <- lift $ asks apiKey
-- Use key for external API call
text $ "Using API key: " <> pack (take 4 key) <> "..."
main :: IO ()
main = scottyOptsT defaultOptions runIO application
where
runIO :: ConfigM a -> IO a
runIO m = runReaderT (runConfigM m) config
config :: Config
config = Config
{"environment" = "Production"
,"apiKey" = "sk_live_abc123xyz"
,"maxConnections" = 100
}
```
--------------------------------
### Interact with Custom Monad Stack Scotty App using Bash
Source: https://context7.com/scotty-web/scotty/llms.txt
This snippet demonstrates using curl to interact with a Scotty application that uses a custom monad stack for state management. It shows how to fetch the current count, increment it, and add a specific amount, observing the state changes. Assumes the Scotty application is running on localhost:3000.
```bash
curl localhost:3000/
# Output: 0
curl localhost:3000/increment
# Redirects to / showing: 1
curl -X POST localhost:3000/add/5
# Output: {"count":6}
```
--------------------------------
### Haskell: File Upload Handling with Scotty
Source: https://context7.com/scotty-web/scotty/llms.txt
Processes multipart form data and file uploads within a Scotty web application. It renders an HTML form for uploads and handles the POST request to save uploaded files. Requires the `network-wai-parse` package.
```haskell
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Network.Wai.Parse (defaultParseRequestBodyOptions, fileName, fileContent)
import qualified Data.ByteString.Lazy as B
import System.FilePath ((>))
import Data.Foldable (for_)
import Control.Exception (SomeException)
main :: IO ()
main = scotty 3000 $ do
get "/" $ do
html $ renderHtml $ H.html $ do
H.body $ do
H.form H.! method "post" H.! enctype "multipart/form-data" H.! action "/upload" $ do
H.input H.! type_ "file" H.! name "file_1"
H.br
H.input H.! type_ "submit"
post "/upload" $ do
filesOpts defaultParseRequestBodyOptions $ \params fs -> do
let fs' = [(fieldName, BS.unpack (fileName fi), fileContent fi)
| (fieldName, fi) <- fs]
-- Save uploaded files
for_ fs' $ \(_, fnam, fpath) -> do
liftIO (do
fc <- B.readFile fpath
B.writeFile ("uploads" > fnam) fc
) `catch` (\(e :: SomeException) -> do
liftIO $ putStrLn $ "Error saving file: " ++ show e
)
-- Return list of uploaded files
json $ map ((fn, fname, _) -> object ["field" .= fn, "name" .= fname]) fs'
-- Simple file list endpoint
get "/files" $ do
fs <- files
json $ map ((fieldName, fileInfo) -> object ["field" .= fieldName]) fs
```
--------------------------------
### Scotty: Streaming and Raw Byte Responses
Source: https://context7.com/scotty-web/scotty/llms.txt
This Haskell code demonstrates two advanced response types in Scotty: streaming responses and raw byte responses. Streaming allows sending data in chunks, useful for large files or real-time updates, while raw provides a way to send arbitrary binary data.
```haskell
{-# LANGUAGE OverloadedStrings #}
import Web.Scotty
import Network.HTTP.Types
import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Lazy as BL
main :: IO ()
main = scotty 3000 $ do
-- Stream response
get "/stream" $ do
setHeader "Content-Type" "text/plain"
stream $ \write flush -> do
write "Chunk 1\n"
flush
liftIO $ threadDelay 1000000
write "Chunk 2\n"
flush
-- Raw bytes
get "/binary" $ do
setHeader "Content-Type" "application/octet-stream"
raw $ BL.pack [0, 1, 2, 3, 4]
```
--------------------------------
### File Upload Handling API
Source: https://context7.com/scotty-web/scotty/llms.txt
Processes multipart form data and file uploads.
```APIDOC
## File Upload Handling API
### Description
This API allows for handling file uploads via multipart form data. It processes uploaded files, saves them to a designated directory, and returns a list of uploaded files.
### POST /upload
#### Description
Receives and processes uploaded files. Files are saved to the 'uploads' directory.
#### Method
POST
#### Endpoint
/upload
#### Parameters
##### Request Body
- **file_1** (file) - Required - The file to upload.
#### Request Example
```bash
curl -F "file_1=@document.pdf" localhost:3000/upload
```
#### Response
##### Success Response (200)
- **Array of objects** - Each object contains details of an uploaded file.
- **field** (string) - The name of the form field for the file.
- **name** (string) - The name of the uploaded file.
#### Response Example
```json
[
{
"field": "file_1",
"name": "document.pdf"
}
]
```
### GET /files
#### Description
Retrieves a list of all files handled by the system.
#### Method
GET
#### Endpoint
/files
#### Response
##### Success Response (200)
- **Array of objects** - Each object represents a file.
- **field** (string) - The name of the form field associated with the file.
#### Response Example
```json
[
{
"field": "file_1"
}
]
```
```
--------------------------------
### Bash: Testing File Upload with curl
Source: https://context7.com/scotty-web/scotty/llms.txt
Tests the file upload functionality of the Scotty application using curl. It uploads a file named 'document.pdf' to the '/upload' endpoint.
```bash
curl -F "file_1=@document.pdf" localhost:3000/upload
# Output: [{"field":"file_1","name":"document.pdf"}]
```
--------------------------------
### Haskell: Custom Exception Handling with Scotty
Source: https://context7.com/scotty-web/scotty/llms.txt
Implements custom exception types (AppError) and demonstrates both global default error handling and local exception catching within Scotty routes. Requires OverloadedStrings, DeriveAnyClass, and LambdaCase language extensions.
```haskell
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE LambdaCase #-}
import Web.Scotty
import Web.Scotty.Trans
import Control.Exception (Exception)
import Data.Typeable
import Network.HTTP.Types
data AppError = Forbidden | NotFound Int | ValidationError String
deriving (Show, Eq, Typeable, Exception)
handleError :: MonadIO m => ErrorHandler m
handleError = Handler $ \case
Forbidden -> do
status status403
html "Access Denied
"
NotFound i -> do
status status404
html $ fromString $ "Can't find " ++ show i ++ "
"
ValidationError msg -> do
status status400
json $ object ["error" .= msg]
main :: IO ()
main = scotty 3000 $ do
-- Set global error handler
defaultHandler handleError
-- Route that throws exception
get "/protected" $ do
throw Forbidden
-- Route with local exception handling
get "/safe/:val" $ do
v <- pathParam "val"
(do
when (v < 0) $ throw (ValidationError "Value must be positive")
json $ object ["value" .= (v :: Int)]
) `catch` (\(ValidationError msg) -> do
text $ "Caught locally: " <> pack msg
)
-- Using next for pattern matching
get "/special/:word" $ do
w :: Text <- pathParam "word"
unless (w == "magic") next
text "You found the magic word!"
get "/special/:word" $ do
w <- pathParam "word"
text $ "Ordinary word: " <> w
```
--------------------------------
### JSON Data Handling
Source: https://context7.com/scotty-web/scotty/llms.txt
Covers handling JSON request bodies and producing JSON responses, including type annotations.
```APIDOC
## GET /user/:id
### Description
Returns a JSON object representing a user with the specified ID.
### Method
GET
### Endpoint
/user/:id
### Parameters
#### Path Parameters
- **id** (string) - The ID of the user.
### Request Example
```bash
curl localhost:3000/user/123
```
### Response
#### Success Response (200)
- **json** (object) - A JSON object with user details.
#### Response Example
```json
{
"userId": 123,
"userName": "Alice",
"userEmail": "alice@example.com"
}
```
## POST /user/create
### Description
Accepts a JSON request body representing a user and returns a JSON confirmation.
### Method
POST
### Endpoint
/user/create
### Parameters
#### Request Body
- **jsonData** (object) - A JSON object conforming to the User data type.
### Request Example
```json
{
"userId": 456,
"userName": "Bob",
"userEmail": "bob@example.com"
}
```
### Response
#### Success Response (200)
- **json** (object) - A JSON object confirming the creation.
#### Response Example
```json
{
"created": "Bob",
"id": 456
}
```
## GET /random
### Description
Returns a JSON array of 20 random integers.
### Method
GET
### Endpoint
/random
### Parameters
### Request Example
### Response
#### Success Response (200)
- **json** (array of integers) - An array of random integers.
#### Response Example
```json
[42, 15, 88, ...]
```
## GET /ints/:is
### Description
Combines a static list of integers with integers provided in the path parameter, returning as JSON.
### Method
GET
### Endpoint
/ints/:is
### Parameters
#### Path Parameters
- **is** (array of integers) - A list of integers provided in the path.
### Request Example
### Response
#### Success Response (200)
- **json** (array of integers) - A combined list of integers.
#### Response Example
```json
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
```
```
--------------------------------
### Random Data API
Source: https://context7.com/scotty-web/scotty/llms.txt
Retrieves a list of random numbers.
```APIDOC
## GET /random
### Description
Retrieves a list of random numbers.
### Method
GET
### Endpoint
/random
### Response
#### Success Response (200)
- **Array of numbers** (array) - A list of random integers.
#### Response Example
```json
[
45,
12,
78,
34,
...
]
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.