PureScript Get Request - How to Make a HTTP Request in PS

by|inArticles||2 min read
GET Request in PureScript
GET Request in PureScript

Usually, when I am building applications in PureScript, I build applications related to web technologies. Those can be SPAs or more exotic Browser Extensions.

In 90% of those I applications I need to interact between the Backend server (or any kind of API) and my application. Since REST is often enough, I use HTTP for this communication.

This article will teach you how to perform a simple HTTP Request in PureScript. We will explore the Library Affjax to perform proper HTTP Requests.

First things first, let's perform a single GET request. Hence, we install the affjax-web library and it's common parts affjax:

spago install affjax affjax-web

With this library in place we can continue with the according imports and perform our first, simple GET request:

module Main

import Data.Either (Either(..))

import Affjax.Web (get)
import Affjax.ResponseFormat as RF
import Affjax.StatusCode (StatusCode(..))

main :: Effect
main = do
  let eResponse = liftAff $ RF.json get "/api/test"
  case eResponse of
    Left error -> -- networt error
    Right response ->
      case response.status of
        StatusCode 200 -> -- this was successful
        _ -> -- other status code, not what we expected

We import the get request from Affjax.Web. Furthermore we make use of the ResponseFormat (qualified by the name RF) and the StatusCode of the Affjax Library.

After performing the GET request, we get back an Either structure. Usually, when the response can not be performed (not existing server endpoint, network error, etc.) we can react to the Left error branch. The error contains further information on what exactly went wrong.

If the request passed to the server, we will get back a response in form of a Right response. Here, we can examine the status code and as well the response data. In my example I used only the 200 status code to keep the code more readable. Pay attention that we pattern match to the StatusCode 200, not only the value 200.

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

Related Articles

© Copyright 2023 - ersocon.net - All rights reservedVer. 402