Skip to content

Instantly share code, notes, and snippets.

@rybla
Created August 20, 2026 17:22
Show Gist options
  • Select an option

  • Save rybla/011f32955d0434413abd552e88a4c5ab to your computer and use it in GitHub Desktop.

Select an option

Save rybla/011f32955d0434413abd552e88a4c5ab to your computer and use it in GitHub Desktop.
Haskell Servant demo of OpenAPI 3.0, swagger-ui, and static file serving
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
-- #region imports
import Data.Aeson (ToJSON)
import Data.OpenApi (OpenApi, ToSchema)
import GHC.Generics (Generic)
import GHC.TypeLits (Symbol, symbolVal)
import Network.Wai.Handler.Warp (run)
import Servant (Get, JSON, Proxy (Proxy), Raw, Server, serve, type (:<|>) (..), type (:>))
import Servant.OpenApi (toOpenApi)
import Servant.Server.StaticFiles (serveDirectoryFileServer)
import Servant.Swagger.UI (SwaggerSchemaUI, swaggerSchemaUIServer)
import System.IO (hPutStrLn, stderr)
-- #endregion
-- #region full api
type FullAPI =
SwaggerSchemaUI SwaggerUiRoute OpenApiSpecRoute
:<|> BusinessAPI
:<|> Raw
type OpenApiSpecRoute = "openapi.json" :: Symbol
type SwaggerUiRoute = "swagger-ui" :: Symbol
-- #endregion
-- #region business API
type BusinessAPI = "api" :> (ItemAPI :<|> UserAPI)
type ItemAPI = "items" :> Get '[JSON] [Item]
data Item = Item
{ itemId :: Int,
itemName :: String
}
deriving (Show, Generic)
instance ToJSON Item
instance ToSchema Item
type UserAPI = "users" :> Get '[JSON] [User]
data User = User
{ userId :: Int,
userName :: String
}
deriving (Show, Generic)
instance ToJSON User
instance ToSchema User
-- #endregion
-- #region server
server :: Server FullAPI
server =
swaggerSchemaUIServer businessOpenApi
:<|> businessServer
:<|> serveDirectoryFileServer "site"
businessServer :: Server BusinessAPI
businessServer =
pure
[ Item i ("Item #" <> show i)
| i <- [1 .. 100]
]
:<|> pure
[ User i ("User #" <> show i)
| i <- [1 .. 100]
]
-- #endregion
-- #region OpenAPI 3.0 document
businessOpenApi :: OpenApi
businessOpenApi = toOpenApi (Proxy @BusinessAPI)
-- #endregion
-- #region entrypoint
main :: IO ()
main = do
let port = 8080 :: Int
let index = "http://localhost:" <> show port
hPutStrLn stderr . unlines $
[ "Server is running.",
" - Index: " <> index,
" - Swagger UI: " <> (index <> "/" <> symbolVal (Proxy @SwaggerUiRoute)),
" - OpenAPI 3.0 Spec: " <> (index <> "/" <> symbolVal (Proxy @OpenApiSpecRoute))
]
run port (serve (Proxy @FullAPI) server)
-- #endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment