Sending HTTP requests in Elm
Elm is a programming language for front-end development. It is a purely functional language that compiles JavaScript. Elm is known for its focus on simplicity, reliability, and maintaining the integrity of web applications. It is often used as an alternative to JavaScript frameworks like React or Angular.
In this Answer, we’ll learn to send HTTP requests in Elm using the GET and POST methods. To find out more about these HTTP protocols, follow this Answer. The ability to send HTTP requests is an important skill for developers as it enables communication between web applications, allowing them to retrieve and exchange data over the internet.
Setting up the Http package
To send any HTTP request in Elm, we must first install the necessary Http package. The installation command is as follows:
elm install elm/http
Note: We don’t have to install anything for the code executables in this Answer, as we’ve already done that.
After the Http package has been installed, we can import and use any Elm code by adding the following line in the code:
import Http
Send a HTTP GET request
Let’s review how we can send an HTTP GET request in Elm. Here’s a sample template for the Elm command to do so:
Http.get{ url = "https://sample-request.com", expect = Http.expectString String}
In the template above:
Http.getis theHttppackage function we’ll use to send theGETrequest.The
urlparameter is where we pass the URL of the server to which we want to send the HTTP request.The
expectparameter is where we pass the logic for interpreting a response body.
Example
Here’s a code executable where we send an HTTP GET request in Elm and get a generic string response from the API, like “Hello from our mock API!”. We can run the demo application by pressing the “Run” button in the widget below. Upon execution, Elm will compile the code to create an index.html file, which will then be served using Node.js, and the app should be available in the output tab. Click the URL next to “Your app can be found at:” to view the application in a new browser tab.
{
"type": "application",
"source-directories": [
"src"
],
"elm-version": "0.19.1",
"dependencies": {
"direct": {
"elm/browser": "1.0.2",
"elm/core": "1.0.5",
"elm/html": "1.0.0",
"elm/http": "2.0.0",
"elm/json": "1.1.3"
},
"indirect": {
"elm/bytes": "1.0.8",
"elm/file": "1.0.5",
"elm/time": "1.0.0",
"elm/url": "1.0.0",
"elm/virtual-dom": "1.0.3"
}
},
"test-dependencies": {
"direct": {},
"indirect": {}
}
}
Explanation
Let’s dive into the code and see how we send a HTTP GET request:
Line 1: This statement essentially makes all the code within the
Mainmodule public, as well as allowing us to compile theMain.elmfile usingelm.Lines 3–7: We import all the required packages, including the
Httppackage for sending HTTP requests.Lines 9–17: We define the
mainfunction, which serves as the entry point for our Elm application.Lines 19–28: We define the model logic for the Elm application.
Lines 19–24: We define the
Error,Loading,Init, andSuccessmodels. TheErrormodel is used to handle the case if something goes wrong with the request, theLoadingmodel handles loading while the request is processed, theInitmodel represents the initial state of the request, and finally, theSuccessmodel handles the response when the request is a success.Lines 26–28: We initialize the application with the
Initstate and no Elm command running.
Lines 30–49: We define the Elm application's update logic on how to update the model and what Elm command to execute.
Lines 31–33: We define two update actions, one for when there’s an Http request result and one for when a button is clicked.
Lines 35–49: We define the logic for the two update actions:
Lines 38–44: This code section is for the action regarding the request result. We check if the request was a success, then we update the model to
Successwith the API response string, and if it was a failure, then we update the model toErrorwith the local error message. We don’t execute any Elm commands in either case.Lines 45–49: This code section is for the action when we click the button. We update the model to
Loading. This action is also where we define theHttp.getfunction. TheHttp.expectString Stringstatement we passed to theexpectparameter means that we expect aStringin the response, and for it to be extracted as theStringtype. In theurlparameter, we pass the URL of our mock API that’s only deployed when the above code is executed.
Lines 51–54: We define the subscription logic for the Elm application.
Lines 56–79: We define the view logic for the Elm application.
Send a HTTP POST request
Let’s see how we can send an HTTP POST request in Elm. Here’s a sample template for the Elm command to do so:
Http.post{ url = "https://sample-request.com", body = Http.emptyBody, expect = Http.expectString String}
In the template above:
Http.postis theHttppackage function to send thePOSTrequest.The
urlparameter is where we pass the URL of the server to which we want to send the HTTP request.The
bodyparameter is where we pass the logic for what to include and how to format the response body.The
expectparameter is where we pass the logic for interpreting a response body.
Example
Here’s the updated code executable where we send an HTTP POST request in Elm and get a customized response from the API based on the text we pass to it in the body. We can run the demo application by pressing the “Run” button in the widget below:
{
"type": "application",
"source-directories": [
"src"
],
"elm-version": "0.19.1",
"dependencies": {
"direct": {
"elm/browser": "1.0.2",
"elm/core": "1.0.5",
"elm/html": "1.0.0",
"elm/http": "2.0.0",
"elm/json": "1.1.3"
},
"indirect": {
"elm/bytes": "1.0.8",
"elm/file": "1.0.5",
"elm/time": "1.0.0",
"elm/url": "1.0.0",
"elm/virtual-dom": "1.0.3"
}
},
"test-dependencies": {
"direct": {},
"indirect": {}
}
}
Explanation
Now, let’s review only the updated code and see how we’ve updated the GET request code to now send a POST requests with the request body containing the user’s input:
Line 25: We define the new
InputValuemodel for handling theStringinput captured in the new text field we added to the view logic.Lines 47–60: This code section is for the action when we click the button. Again, we update the model to
Loading, but this time, we check what value is stored in theInputValuemodel, and based on that, we modify ourHttp.postfunction:Line 52: By passing the
Http.stringBody "text/plain" inputValuestatement to thebodyparameter, we instruct Elm that the request body should include theinputValuestring in thetext/plainformat.Line 57: By passing the
Http.emptyBodystatement to thebodyparameter, we instruct Elm that the request body should include nothing and be empty. This is useful when we don’t want to pass anything in the body of aPOSTrequest.
Lines 61–62: We define the
UserInputaction to update the model toInputValuewith the user’s input string.
Free Resources