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
app = Flask(__name__)
@app .route( "/" )
def showHomePage():
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
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 {
private TextView pagenameTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pagenameTextView = findViewById(R.id.pagename);
OkHttpClient okHttpClient = new OkHttpClient();
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(MainActivity. this , "server down" , Toast.LENGTH_SHORT).show();
pagenameTextView.setText( "error connecting to the server" );
}
});
}
@Override
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
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
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();
RequestBody formbody
= new FormBody.Builder()
.add( "sample" , dummyText)
.build();
.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 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 F
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
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 Build a ChatGPT Like App in Android using OpenAI API?
Chat GPT is nowadays one of the famous AI tools which are like a chatbot. This chatbot answers all the queries which are sent to it. In this article, we will be building a simple ChatGPT-like android application by integrating the OpenAI API(ChatGPT) where we can ask any question and get an appropri
5 min read
How to Build a Book Library App using Google Books API in Android?
If you are looking for building a book library app and you want to load a huge data of books then for adding this feature, you have to use a simple API which is provided by Google, and of course, it's free. In this article, we will take a look at the implementation of this API in our Android App. Wh
15+ 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
10 min read
How to Add Data to Back4App Database in Android?
Prerequisite: How to Connect Android App with Back4App? Back4App is an online database providing platform that provides us services with which we can manage the data of our app inside the database. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update,
4 min read
How to Build a Sticky Notes Application in Android Studio?
We as humans tend to forget some small but important things, and to resolve this we try to write those things up and paste them somewhere, we often have eyes on. And in this digital era, the things we are most likely to see are laptop, computer, or mobile phone screens. For this, we all have once us
11 min read
Android - Build a Book Library App using Kotlin
There are so many apps that are present in the play store which provides details related to different books inside it. Book Library is considered one of the basic applications which a beginner can develop to learn some basic concepts within android such as JSON parsing, using recycler view, and othe
11 min read