Quickstarters
Feature Overview
How to Build a Backend for Flask?
41 min
introduction in this tutorial, you’ll learn how to build a backend for flask using back4app flask is a lightweight backend framework that handles http requests with ease, and it works efficiently in debug mode during development 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 for your flask 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 we will use python code to connect flask to the back4app parse server 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 flask development environment you can install flask via pip install flask ensure you have python 3 7+ installed on your machine pip install parse this python package allows your flask app to interact with back4app’s parse server familiarity with python and flask concepts flask official documentation https //flask palletsprojects com/en/2 2 x/ if you’re new to flask, review the 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 flask environment ready will help you follow along more easily step 1 – creating a new project on back4app and connecting create a new project the first step in building your flask 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 , “flask backend tutorial”) once the project is created, you will see it listed in your back4app dashboard this project is the foundation of all backend configurations connect the parse sdk to flask back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more connecting your flask application to back4app involves installing the parse python package 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 rest api key if needed) you will also find the parse server url (often in the format https //parseapi back4app com ) install the parse python sdk in your flask environment by running pip install parse initialize parse in your flask application create a file (e g , parse config py ) in a directory called app or wherever you store your backend modules parse config py import parse \# replace the placeholders with your back4app credentials parse application id = "your application id" parse client key = "your client key" parse server url = "https //parseapi back4app com" then, in your main flask app file (e g , app py ), you can import flask app flask modules along with your parse config from flask import flask, request, jsonify import parse config # this ensures parse is already set up app = flask( name ) @app route('/') def index() return "hello, flask + back4app!" if name == ' main ' app run(debug=true) # the debug mode helps in local development server by completing this step, you have established a secure connection between your flask front end routes and the back4app backend all requests and data transactions are securely routed through the parse python code, reducing the complexity of manual rest or graphql calls (though you can still use them when needed) step 2 – setting up the database creating a data model before we start, let’s talk about setting up the database you can design your data schema in the back4app dashboard or let parse create it on the fly for instance, you might create a class named “todo” with fields like title and iscompleted 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, like string , number , boolean , object , date , file , pointer , array , relation , geopoint , and polygon you can choose the appropriate type for each field creating a data model using the ai agent if you prefer an automated approach, you can also use back4app’s ai agent open the ai agent from your app dashboard describe your data model in simple language (e g , “create a todo class with title and iscompleted fields at back4app ”) let the ai agent create the schema for you reading and writing data using sdk in flask, you can create and fetch data by importing parse from your parse config py initialization from flask import flask, request, jsonify import parse import parse config app = flask( name ) @app route('/create todo', methods=\['post']) def create todo() data = request get json() # import json to parse the payload title = data get('title') is completed = data get('iscompleted', false) todo = parse object factory('todo') todo item = todo() todo item title = title todo item iscompleted = is completed try saved todo = todo item save() return jsonify({"success" true, "objectid" saved todo objectid}), 200 except exception as e return jsonify({"error" str(e)}), 400 @app route('/fetch todos', methods=\['get']) def fetch todos() todo = parse object factory('todo') query = todo query try todos = query find() \# convert to json compatible response results = \[{"objectid" t objectid, "title" t title, "iscompleted" t iscompleted} for t in todos] return jsonify(results), 200 except exception as e return jsonify({"error" str(e)}), 400 if name == ' main ' app run(debug=true) this flask app file handles http requests to create and read todo items in your back4app database reading and writing data using rest api if you prefer direct rest calls, you can test with curl from the command line 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 reading and writing data using graphql api likewise, back4app provides a graphql endpoint for example mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } working with live queries (optional) if you need real time updates , back4app provides live queries in a flask scenario, you’d typically use a separate client side or server side subscription library that can maintain a websocket connection to back4app’s live query server enable live queries in your back4app dashboard under your app’s server settings use a parse livequery client that connects to wss\ //your subdomain here b4a io and listens for create/update/delete events step 3 – applying security with acls and clps brief overview back4app provides access control lists (acls) and class level permissions (clps) to lock down data acls apply to individual objects, while clps apply to the entire class this helps you restrict or allow read/write operations per user, role, or the public setting up class level permissions 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” or “no access ” configuring acls in code you can apply acls in the python code @app route('/create private todo', methods=\['post']) def create private todo() data = request get json() user id = data get('userid') title = data get('title') \# assume you have a pointer to the user or a way to get user from id parseuser = parse user user query = parseuser query user obj = user query get(user id) todo = parse object factory('todo') todo item = todo() todo item title = title acl = parse acl() acl setreadaccess(user obj, true) acl setwriteaccess(user obj, true) acl setpublicreadaccess(false) acl setpublicwriteaccess(false) todo item acl = acl saved todo = todo item save() return jsonify({"success" true, "objectid" saved todo objectid}), 200 step 4 – writing cloud code functions why cloud code cloud code is perfect for running python code (or javascript in other scenarios) server side, so you don’t have to host your own infrastructure you can run tasks like validating data, performing complex calculations, or integrating with external services directly from the parse server example function because the default cloud code environment for back4app uses node js, you would write your cloud code in javascript however, you can still trigger these server side scripts from your flask app for instance, a node js cloud function might look like 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 use the back4app cli https //www back4app com/docs/local development/parse cli to deploy your cloud code \# step 1 install the cli curl https //raw\ githubusercontent com/back4app/parse cli/back4app/installer sh | sudo /bin/bash \# step 2 configure your account key b4a configure accountkey \# step 3 deploy your code b4a deploy alternatively, you can deploy via the back4app dashboard by pasting your js code into cloud code > functions and clicking “deploy ” calling your function in flask, you can call that cloud function using rest import requests @app route('/text length', methods=\['post']) def get text length() data = request get json() text = data get('text') url = "https //parseapi back4app com/functions/calculatetextlength" headers = { "x parse application id" "your app id", "x parse rest api key" "your rest api key", "content type" "application/json" } payload = {"text" text} response = requests post(url, json=payload, headers=headers) return jsonify(response json()), response status code step 5 – configuring authentication enable or set up user authentication in the back4app dashboard back4app leverages the user class by default parse handles password hashing, session tokens, and secure storage you can manage these features in your app settings code samples @app route('/signup', methods=\['post']) def sign up user() data = request get json() username = data get('username') password = data get('password') email = data get('email') user = parse user() user username = username user password = password user email = email try user sign up() return jsonify({"success" true}), 200 except exception as e return jsonify({"error" str(e)}), 400 @app route('/login', methods=\['post']) def log in user() data = request get json() username = data get('username') password = data get('password') try parse user login(username, password) return jsonify({"success" true}), 200 except exception as e return jsonify({"error" str(e)}), 400 social login back4app and parse can integrate with social providers like google, apple, or facebook setup details vary, so refer to the official parse social login docs https //www back4app com/docs/platform/sign in with apple step 6 – handling file storage setting up file storage you can upload files to your parse database from flask by creating a parse file() object in the node based environment, or you may use direct rest calls from python if you store references to these files in your classes, they become easily retrievable @app route('/upload file', methods=\['post']) def upload file() file = request files\['file'] # from an html form or an api call file name = file filename url = "https //parseapi back4app com/files/" + file name headers = { "x parse application id" "your app id", "x parse rest api key" "your rest api key", "content type" file content type } response = requests post(url, data=file read(), headers=headers) return jsonify(response json()), response status code example after uploading a file, you’ll receive a file url that you can store in your database you can then render or reference that file in your html template as needed step 7 – email verification and password reset overview email verification ensures valid email addresses, and password reset helps users regain account access securely back4app dashboard configuration go to your email settings in the back4app dashboard enable email verification and configure email templates enable password reset to send password recovery links to the user’s email code/implementation once enabled, any new user signing up with an email receives a verification link for password reset, you can call parse’s built in methods via rest or from your flask routes step 8 – scheduling tasks with cloud jobs what cloud jobs do cloud jobs let you schedule background tasks like cleaning up data or sending periodic emails for example, you can delete old records every day without user intervention 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); } }); then, from your back4app dashboard go to app settings > server settings > background jobs schedule this job to run daily or at your preferred interval step 9 – integrating webhooks definition webhooks let your back4app app send data to external services whenever certain triggers occur this is useful for integrations with payment gateways, slack, analytics, or any third party services configuration navigate to the webhooks configuration in your back4app dashboard > more > webhooks add a new webhook set the endpoint (e g , https //your external service com/webhook endpoint https //your external service com/webhook endpoint ) select the triggers for which the webhook will fire example if you want to notify a slack channel whenever a new record is created in “todo,” set the slack webhook url then, whenever a new todo is saved, slack will receive a post request containing its details step 10 – exploring the back4app admin panel the back4app admin app provides a user friendly interface for non technical members of your team it’s a model centric interface for crud operations and enterprise level tasks where to find it go to your app dashboard select more > admin app and enable it create an admin user and pick a subdomain to host the panel once enabled, you can log in with your admin credentials to manage data more conveniently—without writing custom endpoints or queries in your python code conclusion by following this comprehensive tutorial, you have created a secure backend for a flask 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 flask backend framework that can return render template files (if desired) and a robust back4app setup, you are now equipped to develop feature rich, scalable, and secure applications you can run your flask run command to start the development server and continue coding command line tasks become straightforward with methods post def routes that accept json payloads next steps build a production ready flask 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