Quickstarters
Feature Overview
How to Build a Backend for Elm?
46 min
introduction in this tutorial, you’ll learn how to build a complete backend for an elm application using back4app we’ll walk through integrating essential back4app features – such as database management, cloud code functions, rest and graphql apis, user authentication, and real time queries (live queries) – to create a secure, scalable, and robust backend that seamlessly communicates with your elm frontend you’ll also see how back4app’s quick setup and intuitive environment can drastically reduce the time and effort compared to manually configuring servers and databases along the way, you’ll gain hands on experience with key functionalities, including advanced security features, scheduling tasks with cloud jobs, and setting up webhooks for external integrations by the end of this tutorial, you’ll be well prepared to enhance this foundational setup into a production ready application or easily incorporate custom logic and third party apis as needed prerequisites to complete this tutorial, you will need a back4app account and a new back4app project getting started with back4app https //www back4app com/docs/get started/new parse app if you do not have an account, you can create one for free follow the guide above to get your project ready basic elm development environment you can set this up by installing elm https //guide elm lang org/install/ ensure you have elm (0 19 or above) installed on your machine familiarity with elm elm official documentation https //guide elm lang org/ if you’re new to elm, review the official docs or a beginner’s tutorial before starting http request library or graphql approach for elm we will use rest and graphql calls from elm, as there is no official parse elm sdk make sure you have the elm/http https //package elm lang org/packages/elm/http/latest/ and, if needed, a graphql library set up make sure you have all of these prerequisites in place before you begin having your back4app project set up and your local elm environment ready will help you follow along more easily step 1 – setting up back4app project create a new project the first step in building your elm backend on back4app is creating a new project if you have not already created one, follow these steps log in to your back4app account click the “new app” button in your back4app dashboard give your app a name (e g , “elm backend tutorial”) once the project is created, you will see it listed in your back4app dashboard this project will be the foundation for all backend configurations discussed in this tutorial connect with back4app from elm back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more since there is no official elm parse sdk, we’ll use rest or graphql calls from our elm application to communicate with the back4app backend retrieve your parse keys in your back4app dashboard, navigate to your app’s “app settings” or “security & keys” section to find your application id , rest api key , and graphql endpoint you will also find the parse server url (often https //parseapi back4app com ) from elm, you can store these credentials in a configuration file or module for example src/config elm module config exposing (applicationid, restapikey, serverurl, graphqlendpoint) applicationid string applicationid = "your application id" restapikey string restapikey = "your rest api key" serverurl string serverurl = "https //parseapi back4app com" graphqlendpoint string graphqlendpoint = "https //parseapi back4app com/graphql" you’ll use these values whenever you make http requests to back4app from elm by completing this step, you have established how to securely connect your elm front end with the back4app backend step 2 – setting up the database saving and querying data with your back4app project set up, you can now start saving and retrieving data via rest or graphql from elm for a simple example, we’ll demonstrate how to create and fetch a todo item using rest from elm we’ll use elm/http https //package elm lang org/packages/elm/http/latest/ to make rest requests here’s a simplified example to create a todo item src/todoapi elm module todoapi exposing (createtodo, fetchtodos) import config exposing (applicationid, restapikey, serverurl) import http import json decode as decode import json encode as encode \ a simplified representation of a todo type alias todo = { objectid string , title string , iscompleted bool } \ encoder for creating a todo createtodoencoder string > bool > encode value createtodoencoder title iscompleted = encode object \[ ( "title", encode string title ) , ( "iscompleted", encode bool iscompleted ) ] \ decoder for todo tododecoder decode decoder todo tododecoder = decode map3 todo (decode field "objectid" decode string) (decode field "title" decode string) (decode field "iscompleted" decode bool) createtodo string > bool > http request todo createtodo title iscompleted = http request { method = "post" , headers = \[ http header "x parse application id" applicationid , http header "x parse rest api key" restapikey , http header "content type" "application/json" ] , url = serverurl ++ "/classes/todo" , body = http jsonbody (createtodoencoder title iscompleted) , expect = http expectjson tododecoder , timeout = nothing , tracker = nothing } fetchtodos http request (list todo) fetchtodos = http request { method = "get" , headers = \[ http header "x parse application id" applicationid , http header "x parse rest api key" restapikey ] , url = serverurl ++ "/classes/todo" , body = http emptybody , expect = http expectjson (decode field "results" (decode list tododecoder)) , timeout = nothing , tracker = nothing } you can then call createtodo or fetchtodos in your elm update function, handle the http responses, and integrate data into your application’s model using rest directly (example in curl) if you prefer testing or want to do quick calls outside of elm, you can use curl curl x post \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"title" "buy groceries", "iscompleted" false}' \\ https //parseapi back4app com/classes/todo using graphql back4app also provides a graphql interface below is a sample graphql mutation for creating a todo mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } in elm, you can use a graphql library or manually craft your http requests to send these mutations and queries, very similar to how we used elm/http above schema design and data types by default, parse allows schema creation on the fly , but you can also define your classes and data types in the back4app dashboard for more control navigate to the “database” section in your back4app dashboard create a new class (e g , “todo”) and add relevant columns, such as title (string) and iscompleted (boolean) back4app also supports various data types string , number , boolean , object , date , file , pointer , array , relation , geopoint , and polygon you can choose the appropriate type for each field or let parse automatically create these columns when you first save an object from your elm app using the rest or graphql approach back4app offers an ai agent that can help you design your data model open the ai agent from your app dashboard or on the menu describe your data model in simple language (e g , “please, create a new todo app at back4app with a complete class schema ”) let the ai agent create the schema for you using the ai agent can save you time when setting up your data architecture and ensure consistency across your application relational data if you have relational data – say, a category object that points to multiple todo items – you can use pointers or relations in parse from elm, you can manage these relationships by including the pointer or relation fields in your rest or graphql calls for example, to add a pointer via rest { "title" "task with category", "category" { " type" "pointer", "classname" "category", "objectid" "your category object id" } } when you query, you can also include pointer data by using the parameter ?include=category in rest or using include in graphql queries live queries for real time updates, back4app provides live queries while there isn’t a native elm package for parse live queries, you can still enable it in your back4app dashboard enable live queries under your app’s server settings use the websocket endpoint for live queries in a specialized client if you’d like to integrate live queries with elm, you could leverage elm websocket (or another custom approach) to subscribe to changes however, this requires more advanced configuration since no official elm live query client exists at the moment step 3 – applying security with acls and clps back4app security mechanism back4app takes security seriously by providing access control lists (acls) and class level permissions (clps) these features let you restrict who can read or write data on a per object or per class basis, ensuring only authorized users can modify your data access control lists (acls) an acl is applied to individual objects to determine which users, roles, or the public can perform read/write operations you can configure acls from elm by including the acl property in your json when creating or updating objects via rest or graphql for instance, to create a private todo, you could set { "title" "private task", "acl" { "user object id" { "read" true, "write" true } } } this prevents anyone but that user from reading or modifying the object class level permissions (clps) clps govern an entire class’s default permissions, such as whether the class is publicly readable or writable, or if only certain roles can access it go to your back4app dashboard , select your app, and open the database section select a class (e g , “todo”) open the class level permissions tab configure your defaults, such as “requires authentication” for read or write, or “no access” for the public these permissions set the baseline, while acls fine tune permissions for individual objects a robust security model typically combines both clps (broad restrictions) and acls (fine grained per object restrictions) for more information go to app security guidelines step 4 – writing and deploying cloud functions cloud code is a feature of the parse server environment that allows you to run custom javascript code on the server side – without needing to manage servers or infrastructure by writing cloud code, you can extend your back4app backend with additional business logic, validations, triggers, and integrations that run securely and efficiently on the parse server how it works when you write cloud code, you typically place your javascript functions, triggers, and any required npm modules in a main js (or app js ) file this file is then deployed to your back4app project, which is executed within the parse server environment all cloud code for your back4app app runs inside the parse server that is managed by back4app, so you don’t have to worry about server maintenance, scaling, or provisioning whenever you update and deploy your main js file, the running parse server is updated with your latest code // main js // import an npm module (e g , axios) const axios = require('axios'); parse cloud define('fetchexternaldata', async (request) => { const url = request params url; if (!url) { throw new error('url parameter is required'); } const response = await axios get(url); return response data; }); you can call these cloud code functions from elm by making a rest request to https //parseapi back4app com/functions/fetchexternaldata typical use cases business logic aggregating data, processing payments, etc data validations ensuring certain fields meet criteria before saving triggers running code before or after save/update/delete actions integrations connecting with external apis or services security enforcement checking roles or user permissions before performing critical operations deploy your function deploying via the back4app cli install the cli (linux/macos example) curl https //raw\ githubusercontent com/back4app/parse cli/back4app/installer sh | sudo /bin/bash configure your account key b4a configure accountkey deploy your cloud code b4a deploy deploying through the dashboard in your app’s dashboard, go to cloud code > functions copy/paste the function into the main js editor click deploy calling your function from elm, you can call a cloud function by making a post request import config exposing (applicationid, restapikey, serverurl) import http import json decode as decode import json encode as encode cloudfunction string > encode value > http request decode value cloudfunction functionname body = http request { method = "post" , headers = \[ http header "x parse application id" applicationid , http header "x parse rest api key" restapikey , http header "content type" "application/json" ] , url = serverurl ++ "/functions/" ++ functionname , body = http jsonbody body , expect = http expectjson decode value , timeout = nothing , tracker = nothing } calculatetextlength string > http request decode value calculatetextlength text = let requestbody = encode object \[ ( "text", encode string text ) ] in cloudfunction "calculatetextlength" requestbody you can also call cloud functions via graphql mutation { calculatetextlength(input { text "hello graphql" }) { result } } step 5 – configuring user authentication user authentication in back4app back4app leverages the parse user class as the foundation for authentication by default, parse handles password hashing, session tokens, and secure storage you can create and log in users via rest or graphql from your elm app setting up user authentication signing up a new user (rest) signupuser string > string > string > http request decode value signupuser username password email = http request { method = "post" , headers = \[ http header "x parse application id" applicationid , http header "x parse rest api key" restapikey , http header "content type" "application/json" ] , url = serverurl ++ "/users" , body = http jsonbody (encode object \[ ( "username", encode string username ) , ( "password", encode string password ) , ( "email", encode string email ) ] ) , expect = http expectjson decode value , timeout = nothing , tracker = nothing } logging in (rest) loginuser string > string > http request decode value loginuser username password = http request { method = "get" , headers = \[ http header "x parse application id" applicationid , http header "x parse rest api key" restapikey ] , url = serverurl ++ "/login?username=" ++ username ++ "\&password=" ++ password , body = http emptybody , expect = http expectjson decode value , timeout = nothing , tracker = nothing } social login integration back4app and parse can integrate with popular oauth providers such as google , facebook , or apple typically, you’ll configure these providers in the back4app dashboard and then make the necessary requests from elm refer to the social login docs https //www back4app com/docs/platform/sign in with apple for detailed setup steps email verification and password reset navigate to the email settings in your back4app dashboard enable email verification to ensure new users verify ownership of their email addresses configure the from address , email templates, and your custom domain if desired step 6 – handling file storage uploading and retrieving files parse includes the parse file class for handling file uploads, which back4app stores securely since we’re using rest from elm, we can do a multi part file upload or attach a base64 encoded file file upload via rest uploadfile string > string > http request decode value uploadfile filename base64content = http request { method = "post" , headers = \[ http header "x parse application id" applicationid , http header "x parse rest api key" restapikey , http header "content type" "text/plain" ] , url = serverurl ++ "/files/" ++ filename , body = http stringbody "text/plain" base64content , expect = http expectjson decode value , timeout = nothing , tracker = nothing } once uploaded, you’ll receive a file url in the response you can store that url in a parse class field or display it in your elm application as needed file security parse server provides configurations to manage file upload security for instance { "fileupload" { "enableforpublic" true, "enableforanonymoususer" true, "enableforauthenticateduser" true } } step 7 – scheduling tasks with cloud jobs cloud jobs cloud jobs in back4app let you schedule and run routine tasks on your backend, like cleaning up old data or sending periodic emails for instance, a job to remove todos older than 30 days might look like // main js parse cloud job('cleanupoldtodos', async (request) => { const todo = parse object extend('todo'); const query = new parse query(todo); const now = new date(); const thirty days = 30 24 60 60 1000; const cutoff = new date(now thirty days); query lessthan('createdat', cutoff); try { const oldtodos = await query find({ usemasterkey true }); await parse object destroyall(oldtodos, { usemasterkey true }); return `deleted ${oldtodos length} old todos `; } catch (err) { throw new error('error during cleanup ' + err message); } }); deploy your cloud code with the new job (via cli or dashboard) go to the back4app dashboard > app settings > server settings > background jobs schedule the job to run daily or as desired step 8 – integrating webhooks webhooks allow your back4app app to send http requests to an external service whenever certain events occur this is powerful for integrating with third party systems like payment gateways (e g , stripe), email marketing tools, or analytics platforms navigate to the webhooks configuration in your back4app dashboard > more > webhooks and then click on add webhook set up an endpoint (e g , https //your external service com/webhook endpoint https //your external service com/webhook endpoint ) configure triggers to specify which events in your back4app classes or cloud code functions will fire the webhook for instance, if you want to notify a slack channel whenever a new todo is created create a slack app that accepts incoming webhooks copy the slack webhook url in your back4app dashboard, set the endpoint to that slack url for the event “new record in the todo class ” add custom http headers or payloads if needed step 9 – exploring the back4app admin panel the back4app admin app is a web based management interface designed for non technical users to perform crud operations and handle routine data tasks without writing any code it provides a model centric , user friendly interface that streamlines database administration, custom data management, and enterprise level operations enabling the admin app enable it by going to app dashboard > more > admin app and clicking on the “enable admin app” button create a first admin user (username/password), which automatically generates a new role (b4aadminuser) and classes (b4asetting, b4amenuitem, and b4acustomfield) in your app’s schema choose a subdomain for accessing the admin interface and complete the setup log in using the admin credentials you created to access your new admin app dashboard once enabled, the back4app admin app makes it easy to view, edit, or remove records from your database – without requiring direct use of the parse dashboard or backend code with configurable access controls, you can safely share this interface with team members or clients who need a clear, point and click way to manage data conclusion by following this comprehensive tutorial, you have created a secure backend for an elm app on back4app configured a database with class schemas, data types, and relationships integrated real time queries (live queries) possibilities for immediate data updates applied security measures using acls and clps to protect and manage data access implemented cloud code functions to run custom business logic on the server side set up user authentication with support for email verification and password resets managed file uploads and retrieval, with optional file security controls scheduled cloud jobs for automated background tasks used webhooks to integrate with external services explored the back4app admin panel for data management with a solid elm frontend and a robust back4app backend, you are now well equipped to develop feature rich, scalable, and secure applications continue exploring more advanced functionalities, integrate your business logic, and harness the power of back4app to save you countless hours in server and database administration happy coding! next steps build a production ready elm app by extending this backend to handle more complex data models, caching strategies, and performance optimizations integrate advanced features such as specialized authentication flows, role based access control, or external apis (like payment gateways) check out back4app’s official documentation for deeper dives into advanced security, performance tuning, and logs analysis explore other tutorials on real time chat applications, iot dashboards, or location based services you can combine the techniques learned here with third party apis to create complex, real world applications