To implement a REST API server in Haskell, you can use the ‘servant‘ library, a powerful and type-safe web library. It allows you to define your API as a type and then implement the server using that type. ‘servant‘ takes care of handling routing, request parsing, and response generation.
Let’s go through a simple example step by step.
1. Set up the environment
First, create a new Haskell project and add the necessary dependencies to your ‘package.yaml‘ file or ‘.cabal‘ file.
dependencies:
- base >= 4.7 && < 5
- servant
- servant-server
- warp # Web server
2. Define the API
Create a new Haskell file, e.g., ‘Main.hs‘. Start by importing the necessary modules:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Data.Proxy
import Servant
import Servant.API
import Servant.Server
import Network.Wai.Handler.Warp (run)
Now, let’s define the API. We will create an API with one route ‘/greet‘ that returns a simple greeting. We define this as a type:
type GreetAPI = "greet" :> Get '[PlainText] String
type API = GreetAPI
api :: Proxy API
api = Proxy
Note that we use ‘:>‘ to describe the path (":>") and "greet" to specify the endpoint, ‘Get‘ for the HTTP method, and ‘’[PlainText]‘ for the content type.
3. Implement the server
Next, we need to implement the server functions that handle each route. For the ‘/greet‘ route, we need to create a function that returns a simple greeting. Pattern match the request types to their corresponding handlers.
greetHandler :: Handler String
greetHandler = return "Welcome to the REST API server!"
server :: Server API
server = greetHandler
4. Running the server
Finally, let’s use the ‘warp‘ web server to serve our API. Define a function ‘runServer‘ that runs the WAI application provided by ‘servant‘.
runServer :: IO ()
runServer = run 8080 (serve api server)
And finally, add the main function:
main :: IO ()
main = do
putStrLn "Starting the server on port 8080..."
runServer
5. Compile and run
Now you can compile and run the application. It will serve the REST API on port 8080. You can test it by sending a request to the ‘/greet‘ endpoint:
$ curl http://localhost:8080/greet
Welcome to the REST API server!
Congratulations! You have just implemented a simple REST API server in Haskell using ‘servant‘. You can now extend the API with more routes and handlers based on your requirements.
As a side note, there are other Haskell libraries available to implement REST APIs, such as ‘scotty‘ and ‘yesod‘. However, the ‘servant‘ library provides stronger compile-time guarantees and is more modular, making it a popular choice in the Haskell ecosystem.