Quickstarters
Feature Overview
How to Build a Backend for Kotlin?
38 min
introduction in this tutorial, you’ll learn how to build a complete backend for an android application (written in kotlin) using back4app we’ll walk through integrating essential back4app features—including 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 android app 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 android/kotlin development environment ensure you have android studio installed on your machine you can follow android studio’s official setup docs https //developer android com/studio if you haven’t set it up yet a minimum of android 4 0 or above in your app’s gradle config typically, you’ll set this in your minsdkversion in your module’s build gradle familiarity with kotlin and basic android concepts android developer docs https //developer android com/docs if you’re new to android or kotlin, review official docs or a beginner’s tutorial before starting make sure you have all of these prerequisites in place before you begin having your back4app project set up and your local android 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 android 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 , “android kotlin 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 the parse sdk back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more integrating your android app with back4app involves adding the parse android sdk dependencies to your gradle files and initializing them with credentials from your back4app dashboard retrieve your parse keys in your back4app dashboard, navigate to your app’s “app settings” or “security & keys” section to find your application id and client key you will also find the parse server url (often in the format https //parseapi back4app com ) add the parse sdk to your build gradle files in your root build gradle (project level) allprojects { repositories { maven { url "https //jitpack io" } } } in your module level build gradle (usually app/build gradle ) dependencies { implementation "com github parse community parse sdk android\ parse\ latest version here" } initialize parse in your android application create a custom application class (e g , app kt ) if you don’t already have one package com example app import android app application import com parse parse import com parse parseinstallation class app application() { override fun oncreate() { super oncreate() // initialize parse parse initialize( parse configuration builder(this) applicationid("your app id") // from back4app dashboard clientkey("your client key") // from back4app dashboard server("https //parseapi back4app com/") build() ) // (optional) track statistics around app opens parseinstallation getcurrentinstallation() saveinbackground() } } next, open your androidmanifest xml and register the custom application class \<?xml version="1 0" encoding="utf 8"?> \<manifest xmlns\ android="http //schemas android com/apk/res/android" package="com example app"> \<application android\ name=" app" android\ icon="@mipmap/ic launcher" android\ label="@string/app name" android\ usescleartexttraffic="true" > \</application> \</manifest> by completing this step, you have established a secure connection between your android (kotlin) front end and the back4app backend all requests and data transactions are securely routed through this sdk, reducing the complexity of manual rest or graphql calls (although you can still use them when needed) step 2 – setting up the database saving and querying data with your back4app project set up and the parse sdk integrated into your android app, you can now start saving and retrieving data below is an example using kotlin to create and fetch data import com parse parseobject import com parse parsequery import com parse savecallback import com parse parseexception // example create a todo item fun createtodoitem(title string, iscompleted boolean) { val todo = parseobject("todo") todo put("title", title) todo put("iscompleted", iscompleted) todo saveinbackground { e parseexception? > if (e == null) { println("todo saved successfully") } else { println("error saving todo ${e localizedmessage}") } } } // example query all todo items fun fetchtodos() { val query = parsequery\<parseobject>("todo") query findinbackground { results, e > if (e == null) { println("fetched todo items ${results size}") } else { println("error fetching todos ${e localizedmessage}") } } } alternatively, you can use back4app’s rest api endpoints 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 back4app also provides a graphql interface mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } these diverse options let you integrate data operations in the way that best suits your development process—whether that’s through the parse sdk, rest, or graphql 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 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 for example, adding a pointer to a category // linking a todo to a category with a pointer fun createtaskforcategory(categoryobjectid string, title string) { val todo = parseobject("todo") val categorypointer = parseobject("category") categorypointer objectid = categoryobjectid todo put("title", title) todo put("category", categorypointer) todo saveinbackground { e > if (e == null) { println("created task with category relationship") } else { println("error creating task ${e localizedmessage}") } } } when you query, you can also include pointer data val query = parsequery getquery\<parseobject>("todo") query include("category") query findinbackground { todos, e > if (e == null) { println("fetched ${todos size} todos with category data") } } this include("category") call fetches category details alongside each todo, making your relational data seamlessly accessible live queries for real time updates, back4app provides live queries you can subscribe to changes in a specific class from your android app enable live queries in your back4app dashboard under your app’s server settings initialize a live query subscription in your code import com parse parselivequeryclient import com parse parsequery import com parse subscriptionhandling val parselivequeryclient = parselivequeryclient factory getclient() val parsequery = parsequery\<parseobject>("todo") val subscriptionhandling subscriptionhandling\<parseobject> = parselivequeryclient subscribe(parsequery) subscriptionhandling handleevent(subscriptionhandling event create) { querytodo, todo > println("new todo created ${todo getstring("title")}") } subscriptionhandling handleevent(subscriptionhandling event update) { querytodo, todo > println("todo updated ${todo getstring("title")}") } subscriptionhandling handleevent(subscriptionhandling event delete) { querytodo, todo > println("todo deleted ${todo getstring("title")}") } whenever a new todo is created, updated, or deleted, the client gets a callback in real time—perfect for collaborative or dynamic apps 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 for example fun createprivatetodo(title string, owneruser parseobject) { val todo = parseobject("todo") todo put("title", title) // create an acl granting read/write access only to the owner val acl = com parse parseacl(owneruser) acl publicreadaccess = false acl publicwriteaccess = false todo acl = acl todo saveinbackground { e > if (e == null) { println("saved private todo") } else { println("error ${e localizedmessage}") } } } class level permissions (clps) clps govern an entire class’s default permissions, such as whether the class is publicly readable or writable 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 step 4 – writing cloud code functions cloud code lets you run custom kotlin like javascript code on parse server (uploaded as js files), without needing to manage server infrastructure this is ideal for business logic, validations, triggers, and external api calls how it works you typically place javascript functions, triggers, and any required npm modules in a main js file this file is deployed to your back4app project and runs in the parse server environment typical use cases business logic data validations triggers (like beforesave , aftersave ) security enforcement integrations with third party apis deploy your function below is a simple cloud code function main js parse cloud define('calculatetextlength', async (request) => { const { text } = request params; if (!text) { throw new error('no text provided'); } return { length text length }; }); deploying via the https //www back4app com/docs/local development/parse cli \# for linux/mac curl https //raw\ githubusercontent com/back4app/parse cli/back4app/installer sh | sudo /bin/bash \# for windows, download the exe from the releases page then configure and deploy b4a configure accountkey b4a deploy calling your function from your android (kotlin) code via the parse sdk import com parse parsecloud import com parse functioncallback import com parse parseexception fun calltextlengthfunction(sometext string) { val params = hashmapof("text" to sometext) parsecloud callfunctioninbackground\<map\<string, any>>("calculatetextlength", params) { result, e > if (e == null) { val length = result\["length"] as int println("text length $length") } else { println("error calling cloud code ${e localizedmessage}") } } } you can also call it via rest or graphql in a similar manner step 5 – configuring authentication user authentication in back4app back4app leverages the parse user class for authentication parse handles secure password hashing, session tokens, and more out of the box setting up user authentication in kotlin, you can create a new user import com parse parseuser fun signupuser(username string, password string, email string) { val user = parseuser() user username = username user setpassword(password) user email = email user signupinbackground { e > if (e == null) { println("user signed up successfully!") } else { println("error signing up user ${e localizedmessage}") } } } log in an existing user fun loginuser(username string, password string) { parseuser logininbackground(username, password) { user, e > if (user != null && e == null) { println("user logged in ${user username}") } else { println("error logging in ${e? localizedmessage}") } } } social logins such as google, facebook, and apple can also be integrated check social login docs https //www back4app com/docs/platform/sign in with apple for details session management parse automatically manages session tokens you can access the current user val currentuser = parseuser getcurrentuser() if (currentuser != null) { println("currently logged in user ${currentuser username}") } else { println("no user is logged in") } and log out parseuser logout() step 6 – handling file storage uploading and retrieving files parse includes the parsefile class for handling file uploads import com parse parsefile import com parse parseexception fun uploadimage(file java io file) { val bytes = file readbytes() val parsefile = parsefile(file name, bytes) parsefile saveinbackground { e parseexception? > if (e == null) { println("file saved ${parsefile url}") } else { println("error uploading file ${e localizedmessage}") } } } file security you can control who can upload or download files by adjusting acls and clps or by using file specific settings in the parse server configuration step 7 – email verification and password reset enable email verification in your back4app dashboard settings configure your from address, email templates, or custom domain if desired use parseuser requestpasswordresetinbackground(email, callback) to trigger a password reset flow in your app step 8 – scheduling tasks with cloud jobs cloud jobs let you automate routine tasks like cleaning data or sending periodic notifications parse cloud job('cleanupoldtodos', async (request) => { const todo = parse object extend('todo') const query = new parse query(todo) // e g , remove todos older than 30 days const cutoff = new date(date now() 30 24 60 60 1000) query lessthan('createdat', cutoff) const oldtodos = await query find({ usemasterkey true }) await parse object destroyall(oldtodos, { usemasterkey true }) return `deleted ${oldtodos length} old todos ` }) schedule the job in your back4app dashboard under server settings > background jobs step 9 – integrating webhooks webhooks allow your back4app app to send http requests to an external service whenever certain events occur add a webhook in your back4app dashboard under more > webhooks configure triggers (e g , after saving a new object) add a url endpoint (like a slack or stripe webhook) step 10 – exploring the back4app admin panel the back4app admin app is a friendly web based interface for non technical users to manage data enable it under app dashboard > more > admin app create your first admin user choose a subdomain to access the admin panel log in to view, edit, or remove records from your database easily conclusion by following this comprehensive tutorial, you have created a secure backend for an android app on back4app configured a database with class schemas, data types, and relationships integrated real time queries (live queries) 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 android (kotlin) front end 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 android 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