How to Build a Simple Android App with Flask Backend?
Last Updated :
27 Oct, 2021
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. The following article will demonstrate how to use Flask for the backend while developing an Android Application.
Step by Step Implementation
Step1: Installing Flask
Open the terminal and enter the following command to install the flask
pip install flask
Step 2: Add OkHttp Dependencies to the build.gradle file
OkHttp is a library developed by Square for sending and receiving HTTP-based network requests. For making HTTP requests in the Android Application we make use of OkHttp. This library is used to make both Synchronous and Asynchronous calls. If a network call is synchronous, the code will wait till we get a response from the server we are trying to communicate with. This may give rise to latency or performance lag. If a network call is asynchronous, the execution won't wait till the server responds, the application will be running, and if the server responds a callback will be executed.
Android Dependencies
Add the following dependencies to the build.gradle file in Android Studio
implementation("com.squareup.okhttp3:okhttp:4.9.0")
Step 3: Working with the AndroidManifest.XML file
Add the following line above <application> tag
<uses-permission android:name="android.permission.INTERNET"/>
Add the following line inside the <application> tag
android:usesCleartextTraffic="true">
Step 4: Python Script
- @app.route("/") is associated with showHomePage() function. Suppose the server is running on a system with IP address 192.168.0.113 and port number 5000. Now, if the URL "http://192.168.0.113:5000/" is entered into a browser, showHomePage function will be executed and it will return a response "This is home page".
- app.run() will host the server on localhost, whereas, app.run(host="0.0.0.0") will host the server on machine's IP address
- By default port 5000 will be used, we can change it using 'port' parameter in app.run()
Python
from flask import Flask
# Flask Constructor
app = Flask(__name__)
# decorator to associate
# a function with the url
@app.route("/")
def showHomePage():
# response from the server
return "This is home page"
if __name__ == "__main__":
app.run(host="0.0.0.0")
Running The Python Script
run the python script and the server will be hosted.
Step 5: Working with the activity_main.xml file
- Create a ConstraintLayout.
- Add a TextView with ID 'pagename' to the Constraint Layout for displaying responses from the server
- So, add the following code to the activity_main.xml file in android studio.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context=".MainActivity">
<TextView
android:id="@+id/pagename"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Firstly, we need an OkHttp Client to make a request
OkHttpClient okhttpclient = new OkHttpClient();
Next, create a request with the URL of the server. In our case, it is "http://192.168.0.113:5000/". Notice '/' at the end of URL, we are sending a request for the homepage.
Request request = new Request.Builder().url("http://192.168.0.113:5000/").build();
Now, make a call with the above-made request. The complete code is given below. onFailure() will be called if the server is down or unreachable, so we display a text in TextView saying 'server down'. onResponse() will be called if the request is made successfully. We can access the response with the Response parameter we receive in onResponse()
// to access the response we get from the server
response.body().string;
Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
// declare attribute for textview
private TextView pagenameTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pagenameTextView = findViewById(R.id.pagename);
// creating a client
OkHttpClient okHttpClient = new OkHttpClient();
// building a request
Request request = new Request.Builder().url("http://192.168.0.113:5000/").build();
// making call asynchronously
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
// called if server is unreachable
public void onFailure(@NotNull Call call, @NotNull IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "server down", Toast.LENGTH_SHORT).show();
pagenameTextView.setText("error connecting to the server");
}
});
}
@Override
// called if we get a
// response from the server
public void onResponse(
@NotNull Call call,
@NotNull Response response)
throws IOException {pagenameTextView.setText(response.body().string());
}
});
}
}
Note:
- Make sure the Android Application runs on a device that is connected to the same network as the system which hosted the server. (if the flask server is running on a machine that is connected to 'ABC' WIFI, we need to connect our android device to the same 'ABC' network)
- If the Application is failing to connect to the server, make sure your firewall allows connections on port 5000. If not, create an inbound rule in firewall advanced settings.
Output:
Android App running
Step 7: Checking Requests Made in Python Editor
If a request is made, we can see the IP address of the device making the request, the time at which the request was made, and the request type(in our case the request type is GET).

POST Request
We can use okhttp client to send data over the server. Add the following line to the import statements
from flask import request
We need to set the method of a route as POST. Let's add a method and associate a route to it. The method prints the text we entered in the android application to the console in pycharm. Add the following lines after the showHomePage() method.
@app.route("/debug", methods=["POST"])
def debug():
text = request.form["sample"]
print(text)
return "received"
The complete script is given below
Python
from flask import Flask
# import request
from flask import request
app = Flask(__name__)
@app.route("/")
def showHomePage():
return "This is home page"
@app.route("/debug", methods=["POST"])
def debug():
text = request.form["sample"]
print(text)
return "received"
if __name__ == "__main__":
app.run(host="0.0.0.0")
Create a DummyActivity.java in Android Studio. This activity will be started once we get a response from the server from the showHomePage() method. Add the following lines in onResponse() callback in MainActivity.java.
Intent intent = new Intent(MainActivity.this, DummyActivity.class);
startActivity(intent);
finish();
Step 1: Working with the activity_dummy.xml file
- Add an EditText with id dummy_text.
- Add a Button with id dummy_send and with the text "send".
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context=".DummyActivity">
<EditText
android:id="@+id/dummy_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:backgroundTint="@color/black"
android:hint="enter any text"
android:textColor="@color/black"
android:textColorHint="#80000000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/dummy_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dummy_text"
app:layout_constraintVertical_bias="0.1" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 2: Working with the DummyActivity.java file
- We use a form to send the data using the OkHTTP client.
- We pass this form as a parameter to post() while building our request.
- Add an onClickListener() to make a POST request.
- If the data is sent, and we get a response, we display a toast confirming that the data has been received.
Below is the code for the DummyActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class DummyActivity extends AppCompatActivity {
private EditText editText;
private Button button;
private OkHttpClient okHttpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy);
editText = findViewById(R.id.dummy_text);
button = findViewById(R.id.dummy_send);
okHttpClient = new OkHttpClient();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String dummyText = editText.getText().toString();
// we add the information we want to send in
// a form. each string we want to send should
// have a name. in our case we sent the
// dummyText with a name 'sample'
RequestBody formbody
= new FormBody.Builder()
.add("sample", dummyText)
.build();
// while building request
// we give our form
// as a parameter to post()
Request request = new Request.Builder().url("http://192.168.0.113:5000/debug")
.post(formbody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(
@NotNull Call call,
@NotNull IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "server down", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.body().string().equals("received")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "data received", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
});
}
}
Output:
Checking Flask Console
Here we can see the android application made a POST request. we can even see the data we send over the server
Similar Reads
How to Build a Weather App in Android?
In this project, we will be building a weather application. This application will show the temperature of a location. To fetch weather information we will need an API. An API(Application Programming Interface) is a function that allows applications to interact and share data using various components
6 min read
How to Build a Simple TikTok Clone Android App using Firebase?
TikTok is a mobile application that can be downloaded on smartphones and tablets. It is available on both iOS and Android operating systems and can be downloaded for free from the respective app stores. TikTok is a social media platform where users can view short video content i.e. 15 to 60 secs. A
5 min read
How to Build a Web App using Flask and SQLite in Python
Flask is a lightweight Python web framework with minimal dependencies. It lets you build applications using Python libraries as needed. In this article, we'll create a Flask app that takes user input through a form and displays it on another page using SQLite.Run the following commands to install Fl
3 min read
How to Build a QR Code Android App using Firebase?
QR (Quick Response) code is a type of two-dimensional barcode that contains information encoded in a pattern of black and white squares. It was first developed in 1994 by a company named Denso Wave. Qr codes can be scanned by a smartphone or a dedicated QR code scanner, which uses the device's camer
6 min read
How to Build a SOS Mobile Application in Android Studio?
The SOS applications are basically advanced emergency apps that can rescue you and/or your loved ones if you and/or they find themselves in a life-threatening emergency situation and need immediate assistance. When you need some personal assistance, you can actually turn on your phone and can call o
15+ min read
How to Connect Android App with Back4App?
Back4App is another famous backend platform that provides backend services for different types of applications whether it may be web, android, or IOS devices. Back4App also provides us similar services to that of Firebase. We have seen using Firebase in Android App. In this article, we will take a l
6 min read
How to Develop Android Apps with Ionic and Capacitor?
Ionic is an open-source UI toolkit for building performant, high-quality mobile apps that work across multiple platforms, such as native iOS, Android, and the web as a Progressive Web App. Ionic uses web technologies â HTML, CSS, and JavaScript â with integrations for popular frameworks like Angular
3 min read
How to Add Authentication to App with Flask-Login
We can implement authentication, login/logout functionality in flask app using Flask-Login. In this article, we'll explore how to add authentication to a Flask app using Flask-Login.To get started, install Flask, Flask-Login, Flask-SQLAlchemy and Werkzeug using this command:pip install flask flask_s
6 min read
How to Create a Basic Widget of an Android App?
Widgets are the micro-version of the application that consists of some functionality of the application that is displayed only on the Home Screens or the Lock Screen. For example, we see Weather, Time, and Google Search Bars on the Home Screen, and FaceLock, and FingerprintLock on the Lock Screen, w
5 min read
How to Create a News App in Android?
Networking is an integral part of android development, especially when building data-driven clients. The java class mainly used for network connections is HttpUrlConnection. The class requires manual management of data parsing and asynchronous execution of requests. For network operations, we are be
9 min read