Quickstarters
Feature Overview
How to Build a Backend for Elixir?
39 min
introduction in this tutorial, you’ll learn how to build a backend for elixir 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 elixir, running on the erlang vm (beam) and leveraging otp (erlang otp), is known for its fault tolerant, concurrent environment, which pairs well with back4app to form a modern, high performance infrastructure you’ll see how back4app’s quick setup and intuitive environment can drastically reduce your time and effort compared to manually configuring servers and databases this includes leveraging pattern matching, plus hooking into elixir’s web framework of choice by the end of this tutorial, you’ll have a solid foundation you can extend into a production ready application or enhance with custom logic and third party apis 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 elixir development environment ensure you have elixir installed on your machine if you plan to use a web framework such as phoenix, see the phoenix installation guide https //hexdocs pm/phoenix/installation html for reference familiarity with elixir concepts elixir official documentation https //elixir lang org/docs html if you’re new to elixir, review these resources or a beginner’s tutorial before starting make sure you have all these prerequisites in place before you begin having your back4app project set up and your local elixir environment ready will help you follow along more smoothly step 1 – creating a new project on back4app and connecting create a new project the first step in how to build a backend for elixir 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 , “elixir 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 connecting via rest or graphql back4app uses the parse platform as a foundation for elixir, there is no official parse sdk at the moment instead, you can easily connect to back4app using the rest or graphql apis in your elixir project, you’ll retrieve your application id and rest or graphql keys from your app’s “app settings” or “security & keys” section in the back4app dashboard configure http requests using an elixir library such as httpoison https //hex pm/packages/httpoison or tesla https //hex pm/packages/tesla for example, to store credentials in a config file ( config/dev exs or similar) config \ my app, \ b4a, app id "your application id", rest key "your rest api key", server url "https //parseapi back4app com" you can then reference these credentials in your code to make rest calls throughout this guide, we’ll showcase how to interact with the back4app database, user system, and other features using standard http or graphql requests step 2 – setting up the database creating a data model in back4app, data is stored in classes you can create a new class in the back4app dashboard 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) creating a data model using the ai agent back4app also provides an ai agent to help you describe and create your data model open the ai agent from your app dashboard or the menu describe your data model in plain language (e g , “please, create a new todo app with a complete class schema ”) let the ai agent create the schema automatically reading and writing data using sdk (if applicable) since elixir does not have an official parse sdk, we’ll skip direct sdk usage instead, we’ll showcase rest , graphql , and live queries approaches below reading and writing data using rest api install an http client like httpoison in your mix exs defp deps do \[ {\ httpoison, " > 1 8"} ] end then, run mix deps get to create (save) a todo object from your elixir application defmodule myapp todo do @moduledoc false require logger alias myapp config def create todo(title, is completed) do url = config server url() <> "/classes/todo" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()}, {"content type", "application/json"} ] body = jason encode!(%{"title" => title, "iscompleted" => is completed}) case httpoison post(url, body, headers) do {\ ok, %httpoison response{status code 201, body resp body}} > logger info("todo created #{resp body}") {\ ok, resp body} {\ ok, %httpoison response{status code status, body error body}} > logger error("error creating todo (#{status}) #{error body}") {\ error, error body} {\ error, error} > logger error("http error #{inspect(error)}") {\ error, error} end end end and to query your todo objects def fetch todos() do url = config server url() <> "/classes/todo" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()} ] httpoison get(url, headers) end reading and writing data using graphql api you can also interact via graphql for example, creating a todo mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } in elixir, you might send this with an http client as well graph query = """ mutation { createtodo(input { fields { title "new from graphql", iscompleted false } }) { todo { objectid title } } } """ url = config server url() <> "/graphql" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()}, {"content type", "application/json"} ] httpoison post(url, jason encode!(%{"query" => graph query}), headers) working with live queries (optional) for real time updates, back4app offers live queries you can enable live queries in your app’s server settings since there’s no native elixir parse client library at the moment, you’d typically connect through a phoenix channel or any custom websocket client to the provided wss\ //your subdomain here b4a io endpoint this can be more advanced, requiring custom coding to handle subscriptions, messages, etc step 3 – applying security with acls and clps brief overview back4app offers access control lists (acls) and class level permissions (clps) to protect and manage data access acls apply to individual objects, while clps apply to the entire class step by step class level permissions (clps) in your back4app dashboard, under database , select a class (e g , “todo”) and open the class level permissions tab adjust settings (e g , “requires authentication” or “no access” for the public) configure acls when creating or updating an object, you can send acl data in your rest or graphql request for instance, specify the acl field in json if you need fine grained per object control for more information, visit the app security guidelines https //www back4app com/docs/security/parse security step 4 – writing cloud code functions why cloud code cloud code lets you run server side logic without managing your own servers with elixir, you usually rely on otp for concurrency, but here you can simply create javascript cloud code in back4app to handle validation, triggers, or custom business logic this code runs on parse server, so you can keep your elixir code focused on client or microservice tasks while the heavy lifting happens in cloud code example function in your main js on the back4app dashboard or using the cli // main js parse cloud define('calculatetextlength', async (request) => { const { text } = request params; if (!text) { throw new error('no text provided'); } return { length text length }; }); deployment deploy via the back4app cli https //www back4app com/docs/local development/parse cli or by pasting into the dashboard under cloud code > functions and clicking deploy calling cloud code from elixir, you might use defmodule myapp cloudfunctions do alias myapp config def calculate text length(text) do url = config server url() <> "/functions/calculatetextlength" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()}, {"content type", "application/json"} ] body = jason encode!(%{text text}) httpoison post(url, body, headers) end end step 5 – configuring authentication enable or set up authentication back4app uses the parse user class for authentication you can manage sign up, login, and password resets easily from elixir, you’ll typically use rest calls defmodule myapp auth do alias myapp config def sign up user(username, password, email) do url = config server url() <> "/users" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()}, {"content type", "application/json"} ] body = jason encode!(%{ username username, password password, email email }) httpoison post(url, body, headers) end def log in user(username, password) do url = config server url() <> "/login?username=#{username}\&password=#{password}" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()} ] httpoison get(url, headers) end end social login back4app supports integration with google, apple, facebook, and more in most cases, you’ll direct users to the oauth flow, then use tokens returned by these providers to complete the parse login see social login docs https //www back4app com/docs/platform/sign in with apple for details step 6 – handling file storage setting up file storage back4app stores files securely from elixir, you’d upload files via rest defmodule myapp filestorage do alias myapp config require logger def upload file(file path) do file name = path basename(file path) url = config server url() <> "/files/#{file name}" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()}, {"content type", "application/octet stream"} ] body = file read!(file path) case httpoison post(url, body, headers) do {\ ok, %httpoison response{status code 201, body resp body}} > logger info("file uploaded #{resp body}") {\ ok, resp body} error > logger error("error uploading file #{inspect(error)}") error end end end you’ll receive a json response with the file url, which you can store in a class (e g , photo ) for reference security considerations you can configure who can upload files in fileupload settings on your back4app project, restricting uploads to authenticated users if desired step 7 – email verification and password reset overview email verification ensures that users own the email address used during sign up password reset lets them recover accounts securely both features are built in on back4app back4app dashboard configuration enable email verification under your app’s “app settings” or “authentication ” configure the from address and email templates enable password reset to let users reset via a link emailed to them code/implementation once enabled in the dashboard, you can trigger password resets defmodule myapp auth do def request password reset(email) do url = config server url() <> "/requestpasswordreset" headers = \[ {"x parse application id", config app id()}, {"x parse rest api key", config rest key()}, {"content type", "application/json"} ] body = jason encode!(%{email email}) httpoison post(url, body, headers) end end step 8 – scheduling tasks with cloud jobs what cloud jobs do cloud jobs let you automate routine tasks like cleaning old data or sending periodic emails you write them in cloud code example // 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 the code go to the back4app dashboard > app settings > server settings > background jobs schedule the job to run daily or at a frequency you choose step 9 – integrating webhooks definition webhooks allow your back4app application to send http requests to an external service (e g , a slack channel or stripe) when certain events occur configuration navigate to the webhooks configuration in your back4app dashboard > more > webhooks set the endpoint (for example, https //your service com/webhook endpoint ) configure triggers such as “new record in the todo class ” example if you want to send data to slack whenever a todo is created, you can add a new webhook pointing to your slack incoming webhook url you might also define webhooks in cloud code by sending custom http requests in triggers like aftersave step 10 – exploring the back4app admin panel where to find it the back4app admin app is a user friendly interface for managing your data you can enable it from app dashboard > more > admin app features create a first admin user , which sets up the b4aadminuser role and additional classes assign a subdomain to access the admin interface log in to view and manage data in a simple interface conclusion by following this tutorial on how to build a backend for elixir with back4app, you have created a secure backend structure on back4app’s platform using elixir for integration set up a database with classes, data types, and relationships used rest/graphql to interact with your data from elixir applied security using acls and clps added custom logic with cloud code functions configured user authentication with email verification and password resets handled file storage and retrieval scheduled background jobs for automation integrated external services with webhooks explored the back4app admin panel for easy data management with elixir’s concurrency model (powered by the erlang vm) and otp, combined with back4app’s scalable and flexible services, you can build highly robust backends continue exploring more advanced features, integrate your business logic, and let back4app help you handle the heavy lifting next steps build a production ready elixir app by layering this backend with your preferred elixir/phoenix web framework integrate advanced features like role based access control or third party apis (payment gateways, messaging services) explore back4app’s official documentation for advanced security, logs, performance tuning, and more check out other tutorials for real time apps, iot dashboards, or location based services with pattern matching and otp concurrency at your disposal, you’re equipped to tackle a wide range of applications!