Quickstarters
Feature Overview
How to Build a Backend for MacOS?
45 min
introduction in this tutorial, you’ll learn how to build a backend for macos using back4app and the parse swift sdk 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 macos application 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 macos application, or easily incorporate custom logic and third party apis as needed mastering this approach will empower you to streamline your workflows and learn how to build a backend for macos quickly and efficiently 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 a macos development environment (xcode) you can install xcode from the mac app store https //apps apple com/us/app/xcode/id497799835 swift package manager or cocoapods for installing the parse swift sdk parse swift documentation https //github com/netreconlab/parse swift basic knowledge of swift and macos app development apple's official documentation https //developer apple com/documentation/swift familiarity with swiftui or appkit is helpful make sure you have all of these prerequisites in place before you begin having your back4app project set up and your local macos development 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 macos 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 , “macos 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 swift sdk back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more connecting your macos application to back4app involves installing the parse swift sdk and initializing it with the 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 (or clientkey ) you will also find the parse server url (often in the format https //parseapi back4app com ) install the parse swift sdk in your macos project if using swift package manager dependencies \[ package(url "https //github com/netreconlab/parse swift git", from "5 0 0") ] if using cocoapods , add this to your podfile pod 'parseswiftog' initialize parse in your macos application (for example, in appdelegate swift if using appkit, or in a swiftui @main struct if building a swiftui app) import parseswift import swiftui @main struct mymacosapp app { init() { task { do { try await parseswift initialize( applicationid "your application id", clientkey "your client key", serverurl url(string "https //parseapi back4app com")! ) } catch { print("error initializing parse \\(error)") } } } var body some scene { windowgroup { contentview() } } } by completing this step, you have established a secure connection between your macos front end (ui) and the back4app backend all requests and data transactions are securely routed through this sdk, reducing the complexity of manual rest or graphql calls (though you can still use them if needed) step 2 – setting up the database saving and querying data with your back4app project set up and the parse swift sdk integrated into your macos app, you can now start saving and retrieving data the simplest way to create an object is to define a struct conforming to parseobject and then call save() struct todo parseobject { // parseobject required properties var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? // custom properties var title string? var iscompleted bool? } func createtodoitem(title string, iscompleted bool) async { var todo = todo() todo title = title todo iscompleted = iscompleted do { try await todo save() print("todo saved successfully ") } catch { print("error saving todo \\(error)") } } func fetchtodos() async > \[todo] { let query = todo query() do { return try await query find() } catch { print("error fetching todos \\(error)") return \[] } } alternatively, you can use back4app’s rest or graphql api 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 swift 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 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 macos app 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 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 swift struct category parseobject { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? // custom fields var name string? } struct todo parseobject { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? var title string? var category pointer\<category>? } func createtaskforcategory(categoryobjectid string, title string) async { let pointer = pointer\<category>(objectid categoryobjectid) var todo = todo() todo title = title todo category = pointer do { try await todo save() print("todo linked to category") } catch { print("error creating task with category relationship \\(error)") } } func fetchtodoswithcategory() async { let query = todo query() include("category") do { let todos = try await query find() print("fetched todo items with category \\(todos)") } catch { print("error fetching todos \\(error)") } } live queries for real time updates, back4app provides live queries by enabling live queries in your back4app dashboard, you can subscribe to changes in a specific class from your macos app enable live queries in your back4app dashboard under your app’s server settings initialize live queries in code (the swift live query client is still in flux, but you can use community driven approaches or watch for official parse swift updates) src/parseconfig swift // example (subject to support in parse swift) // live query’s subdomain // parseswift configuration livequeryserverurl = url(string "wss\ //your subdomain here b4a io")! once subscribed, you’d receive notifications whenever a new todo is created, updated, or deleted this is especially valuable for collaborative or highly interactive desktop apps where multiple users or processes need to see the latest data instantly 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, if your macos app has a concept of “private tasks” for the currently logged in user import parseswift func createprivatetodo(title string) async { guard let currentuser = user current else { return } var todo = todo() todo title = title // create an acl granting read/write access only to the owner var acl = parseacl() acl setreadaccess(currentuser, value true) acl setwriteaccess(currentuser, value true) todo acl = acl do { try await todo save() print("private todo saved") } catch { print("error saving private todo \\(error)") } } when you save the object, it has an acl that prevents anyone but the specified user from reading or modifying it 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 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 your own 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 file you then deploy this file to your back4app project, and it runs in the parse server environment this allows you to keep sensitive logic server side typical use cases business logic calculations or transformations before saving data data validations ensure certain fields meet criteria triggers perform actions when data changes integrations connect with external apis (e g , payments, notifications) example 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 back4app cli install the cli 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 calling your function from macos using swift import parseswift func gettextlength(text string) async { do { let result = try await parsecloud callfunction("calculatetextlength", with \["text" text]) if let resultdict = result as? \[string any], let length = resultdict\["length"] as? int { print("text length \\(length)") } } catch { print("error calling cloud function \\(error)") } } you can also call it via rest or graphql, the same way as in other frameworks step 5 – configuring user authentication user authentication in back4app back4app leverages the parseuser class as the foundation for authentication by default, parse handles password hashing, session tokens, and secure storage, so you don’t have to set up complex security flows manually setting up user authentication in a macos application, you can create a new user with struct user parseuser { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? // default properties var username string? var email string? var emailverified bool? var password string? var authdata \[string \[string string]?]? } func signupuser(username string, password string, email string) async { var newuser = user() newuser username = username newuser password = password newuser email = email do { newuser = try await newuser signup() print("user signed up successfully!") } catch { print("error signing up user \\(error)") } } func loginuser(username string, password string) async { do { let user = try await user login(username username, password password) print("user logged in \\(user)") } catch { print("error logging in user \\(error)") } } via rest, a login might look like curl x get \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ g \\ \ data urlencode 'username=alice' \\ \ data urlencode 'password=secret123' \\ https //parseapi back4app com/login session management after a successful login, parse creates a session token you can access the currently logged in user if let currentuser = user current { print("currently logged in user \\(currentuser username ?? "no username")") } else { print("no user is logged in") } logging out do { try await user logout() } catch { print("error logging out \\(error)") } social login integration you can integrate popular providers like google, apple, or facebook by configuring authdata detailed instructions vary, so refer to social login docs https //www back4app com/docs/platform/sign in with apple email verification and password reset to enable email verification and password reset navigate to the email settings in your back4app dashboard enable email verification configure the from address , email templates, and your custom domain if desired this improves account security by validating user emails and providing a password recovery method step 6 – handling file storage uploading and retrieving files parse includes the parsefile class for handling file uploads, which back4app stores securely func uploadfile(data data) async > parsefile? { let file = parsefile(name "doc txt", data data) do { let savedfile = try await file save() print("file saved ", savedfile url ?? "no url") return savedfile } catch { print("error uploading file ", error) return nil } } attach it to an object struct photo parseobject { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? var imagefile parsefile? } func createphotoobject(file parsefile) async { var photo = photo() photo imagefile = file do { try await photo save() print("photo object saved!") } catch { print("error saving photo ", error) } } file security you can configure file upload security in your parse server settings for example, controlling which users can upload or delete files keep in mind that if you share the file’s url, anyone with that url can access it unless you’ve set stricter server side rules step 7 – email verification and password reset overview email verification and password resets are critical for secure user management we’ve already touched on it under step 5 , but as a reminder enable these features in the back4app dashboard (email settings) configure “enable email verification” and “password reset” email templates test the flow from your macos app step 8 – scheduling tasks with cloud jobs cloud jobs cloud jobs let you schedule and run routine tasks on your backend, like sending periodic emails or cleaning data for 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); const oldtodos = await query find({ usemasterkey true }); await parse object destroyall(oldtodos, { usemasterkey true }); return `deleted ${oldtodos length} old todos `; }); deploy your cloud code with the new job go to the back4app dashboard > app settings > server settings > background jobs schedule the job (e g , daily) step 9 – 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, email marketing tools, or analytics platforms navigate to the webhooks configuration in your back4app dashboard > more > webhooks set up an endpoint (e g , 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 slack 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 ” step 10 – 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 “enable admin app ” create a first admin user , which automatically generates a new role ( b4aadminuser ) and relevant classes 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 conclusion by following this comprehensive tutorial, you have created a secure backend for a macos 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 macos front end and a robust back4app backend, you are now well equipped to develop feature rich, scalable, and secure desktop 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 next steps build a production ready macos 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 communication, iot dashboards, or location based services combine the techniques learned here with third party apis to create complex, real world applications